如何在iPhone中的NSMutableArray中创建NSDictionary?

时间:2011-01-31 10:19:30

标签: iphone nsmutablearray nsmutabledictionary

我有一个NSMutableDictionary,它包含用户详细信息。我使用了解析并从MutableDictionary获取数据。

feedDictionary是, {

"city = New York",
"phone = 111111",
"email = aaa@test.com",
"year = 1986",
"degree = Undergraduate"

}

我已将所有值添加到FeedArray中,并且我想为FeedArray创建两个字典。因为我已在节表视图中显示了数据。所以表格部分数据是 - 第1节 - [城市,电话,电子邮件]和第2节[年份,学位]。因为如果任何数据都是nil,那么我不应该删除该部分中的特定行。所以我想检查数据,数据是否为零。

编辑:

在我添加到FeedArray之前,我想检查字符串是否为零。如果字符串为nil,那么我不应该添加数组,如果数据不是nil,则只添加到FeedArray。

[self isEmpty:[feedDictionary valueForKey:@"city"]]?:[feedArray addObject:[feedDictionary valueForKey:@"city"]]; //section1

[self isEmpty:[feedDictionary valueForKey:@"phone"]]?:[feedArray addObject:[feedDictionary valueForKey:@"phone"]]; //section1

[self isEmpty:[feedDictionary valueForKey:@"email"]]?:[feedArray addObject:[feedDictionary valueForKey:@"email"]]; //section1

[self isEmpty:[feedDictionary valueForKey:@"year"]]?:[feedArray addObject:[feedDictionary valueForKey:@"year"]]; //section2

[self isEmpty:[feedDictionary valueForKey:@"degree"]]?:[feedArray addObject:[feedDictionary valueForKey:@"degree"]]; //section2

 -(BOOL) isEmpty :(NSString*)str{
      if(str == nil || [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)
    return YES;
return NO;

}

预期输出是,

我的数组是5(

section1{
"city = New York",
"phone = 111111",
"email = aaa@test.com",
}
 section2
{

"year = 1986",
"degree = Undergraduate"e"
}

) 那么如何为Mutable Array创建字典呢?所以请指导我。

谢谢!

1 个答案:

答案 0 :(得分:2)

NSArray *section0Keys = [NSArray arrayWithObjects:@"city", @"phone", @"email", nil];
NSMutableArray *section0 = [[[feedDictionary objectsForKeys:section0Keys notFoundMarker:[NSNull null]] mutableCopy] autorelease];
if ([section0 indexOfObject:[NSNull null]] != NSNotFound) {
    isValid = NO;
}
// you don't need this if you don't care for invalid arrays.
[section0 removeObjectsInArray:[NSArray arrayWithObject:[NSNull null]]];

NSArray *section1Keys = [NSArray arrayWithObjects:@"year", @"degree", nil];
NSMutableArray *section1 = [[[feedDictionary objectsForKeys:section1Keys notFoundMarker:[NSNull null]] mutableCopy] autorelease];
if ([section1 indexOfObject:[NSNull null]] != NSNotFound) {
    isValid = NO;
}
[section1 removeObjectsInArray:[NSArray arrayWithObject:[NSNull null]]];

self.dataArray = [NSArray arrayWithObjects:
section0,
section1,
nil];

您的UITableView数据源方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.dataArray count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.dataArray objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    /.../
    cell.textLabel.text = [[self.dataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    return cell;
}

编辑:我想我误解了你编辑过的问题。你的代码一见钟情。