views:

219

answers:

2

hi all,

i'm having NSMutableArray which containing student info, now i just want to extract student name and their average mark only, so what i did

    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]);
}

i'm able to run this for first time, but when i make auto scan, i can exe for 1st, 2nd, 3rd loop but then apps terminate show as below,

2009-12-02 14:57:37.908 AppBuzz[13073:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFArray insertObject:atIndex:]: attempt to insert 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 ) terminate called after throwing an instance of 'NSException' Program received signal: “SIGABRT”.

how this can be improve

thanks

A: 

Since it looks like students is a Cocoa collection, you can use the following:

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

See the KVC Set and Array Operators for more info.

sbooth
+1  A: 

Do you understand assertions?

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