0

我有包含学生信息的 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]);
}

我可以第一次运行它,但是当我进行自动扫描时,我可以执行第一个、第二个、第三个循环,但是应用程序终止显示如下,

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]堆栈:(820145437,837578260,819694387,819694291,814683071,814716415,814716245,17529,24097,814480795,819893443,819891231,858682228,861592624,861585968,8997,8860)终止称为抛出“NSException”实例后,程序收到信号:“SIGABRT”。

如何改进

谢谢

4

2 回答 2

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];
    }
}
...
于 2009-12-02T07:39:17.207 回答
0

由于学生看起来像是 Cocoa 集合,因此您可以使用以下内容:

NSArray *studentNames = [students valueForKey:@"name"];

有关详细信息,请参阅 KVC集和数组运算符

于 2009-12-02T07:17:26.953 回答