将单个NSMutableArray分成两部分,以便我可以在UITableView的每个部分中设置每个部分
我想使用多个部分功能UITableView
。我有一个单独的NSMutableArray
,它由字典格式的数据组成。在该字典中有一个键值为'0'和'1'。 我想创建两个单独的NSMutableArray
,以便我可以在不同部分相应地分配它们。将单个NSMutableArray分成两部分,以便我可以在UITableView的每个部分中设置每个部分
例如:
if (indexPath.section==0) {
NSDictionary *Data = [roomList1 objectAtIndex:indexPath.row];
} else {
NSDictionary *Data = [roomList2 objectAtIndex:indexPath.row];
}
假设在你的字典中的值始终设置,你可以这样做:
NSMutableArray *firstArray = [NSMutableArray new];
NSMutableArray *secondArray = [NSMutableArray new];
for (NSDictionary *dictionary in yourArray) {
if ([dictionary objectForKey:@"yourValue"] isEqualToString: @"0") {
[firstArray addObject:dictionary];
} else if ([dictionary objectForKey:@"yourValue"]isEqualToString: @"1") {
[secondArray addObject:dictionary];
}
}
您可以使用此
- (NSDictionary *)groupObjectsInArray:(NSArray *)array byKey:(id <NSCopying> (^)(id item))keyForItemBlock
{
NSMutableDictionary *groupedItems = [NSMutableDictionary new];
for (id item in array) {
id <NSCopying> key = keyForItemBlock(item);
NSParameterAssert(key);
NSMutableArray *arrayForKey = groupedItems[key];
if (arrayForKey == nil) {
arrayForKey = [NSMutableArray new];
groupedItems[key] = arrayForKey;
}
[arrayForKey addObject:item];
}
return groupedItems;
}
编号:Split NSArray into sub-arrays based on NSDictionary key values
使用这样
NSMutableArray * roomList1 = [[NSMutableArray alloc] init];
NSMutableArray * roomList2 = [[NSMutableArray alloc] init];
for(int i = 0;i< YourWholeArray.count;i++)
{
if([[[YourWholeArray objectAtIndex:i] valueForKey:@"YourKeyValueFor0or1"] isEqualToString "0"])
{
[roomList1 addObject:[YourWholeArray objectAtIndex:i]];
}
else if([[YourWholeArray objectAtIndex:i] valueForKey:@"YourKeyValueFor0or1"] isEqualToString "1"])
{
[roomList2 addObject:[YourWholeArray objectAtIndex:i]];
}
}
我会使用isEqualToString:当你比较字符串 – LoVo
但这是终止应用程序与此错误:***由于未捕获的异常'NSInvalidArgumentException',原因:' - [__ NSArrayI isEqualToString:]:无法识别的选择器发送到实例0x78e0b210' – Subso
添加一些示例代码的响应.. – Madhumitha
试试这个方法: -
NSMutableArray *getdata=[[NSMutableArray alloc]init];
getdata=[results objectForKey:@"0"];
NSMutableArray *getdata2=[[NSMutableArray alloc]init];
getdata2=[results objectForKey:@"1"];
use this two array and populate the section with now of rows at indexpathrow
define number of section 2
if (section==0){
getdata
}
else{
getdata2
}
NSMutableArray *roomList1 = [[NSMutableArray alloc] init];
NSMutableArray *roomList2 = [[NSMutableArray alloc] init];
for (NSString *key in [myDictionary allKeys]) {
if (myDictionary[key] isEqualToString: @"0") {
[roomList1 addObject: myDictionary[key]];
} else {
[roomList2 addObject: myDictionary[key]];
}
}
什么是在字典中的值0/1的关键。你可以使用谓词来获得0和1的不同值的数组。 – Chetan
你能告诉我一些json数据吗? – Mahesh
LIST :( { d = “1”; 克= “本地”; ID = 9550; N = testapp1; 的可用=; },{ d = “0” 克= “本地”; ID = 5319; N = chatplus1; S =远; }, }) – Subso