我有NSMutableArray,其中包含学生信息,现在我只想提取学生姓名及其平均分数,所以我做了什么
NSMutableArray *stuCollection = [[NSMutableArray alloc] initWithCapacity:[students count]];
for (int i = 0; i < [students count]; i++)
{
if([students objectAtIndex:i] != NULL)
{
NSDictionary *dic = [students objectAtIndex:i];
NSString *temp = [dic objectForKey:@"name"];
[stuCollection addObject:name];
}
}
for(int j=0; j< [stuCollection count]; j++)
{
NSLOG(@"Name %@",[stuCollection objectAtIndex:j]);
}
我可以第一次运行它,但是当我进行自动扫描时,我可以执行第1次,第2次,第3次循环但是应用程序终止显示如下,
2009-12-02 14:57:37.908 AppBuzz [13073:207] *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'* - [NSCFArray insertObject:atIndex:]:试图插入nil' 2009-12-02 14:57:37.916 AppBuzz [13073:207] Stack :( 820145437, 837578260, 819694387, 819694291, 814683071, 814716415, 814716245, 17529, 24097, 814480795, 819893443, 819891231, 858682228, 861592624, 861585968, 8997, 8860 ) 抛出'NSException'实例后终止调用 程序收到信号:“SIGABRT”。
如何改进
感谢
答案 0 :(得分:1)
你理解断言吗?
assert(students);
assert([students count]);
NSMutableArray * stuCollection = [[NSMutableArray alloc] initWithCapacity:[students count]];
assert(stuCollection);
for (int i = 0; i < [students count]; i++) {
if ([students objectAtIndex:i] != NULL) {
NSDictionary * dic = [students objectAtIndex:i];
assert(dic);
NSString * temp = [dic objectForKey:@"name"];
assert(temp);
assert(name);
[stuCollection addObject:name];
}
}
...
答案 1 :(得分:0)
由于看起来学生是Cocoa集合,您可以使用以下内容:
NSArray *studentNames = [students valueForKey:@"name"];
有关详细信息,请参阅KVC Set and Array Operators。