2009-12-02 100 views
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, “SIGABRT”: 819893443, 819891231, 858682228, 861592624, 861585968, 8997,) 扔 'NSException' 程序接收到的信号的一个实例后终止调用。

这可怎么提高

感谢

回答

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]; 
    } 
} 
... 
0

因为它看起来像学生是可可集合,可以使用以下命令:

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

见KVC Set and Array Operators更多信息。