Linjiong Cai
Linjiong Cai

Reputation: 83

Adding strings to an array in for loop and not overwrite the value in objective-c

I define a NSMutableArray *nameArray in .h file. And add strings using this nameArray in a for loop in .m file like below:

for (int i=0; i<[data count]; i++) {        
  NSDictionary* place = [data objectAtIndex:i];        
  NSString *name=[place objectForKey:@"name"];        
  _nameArray = [[NSMutableArray alloc] init];
  [_nameArray addObject:name];
}        
NSLog(@"After loop, Name is %@", _nameArray);

Actually, it should have several names in this array. But why it only output one name which was added in the array last?

Upvotes: 0

Views: 698

Answers (1)

Seega
Seega

Reputation: 3390

You must create your array outside the loop, that is your problem.

// Init array
_nameArray = [[NSMutableArray alloc] init];
// Fill array
for (int i=0; i<[data count]; i++) {        
  NSDictionary* place = [data objectAtIndex:i];        
  NSString *name=[place objectForKey:@"name"];  
  [_nameArray addObject:name];
}   
// Log array     
NSLog(@"After loop, Name is %@", _nameArray);

All of your objects are added to an own array and only the last array will not be overwritten and is therefore in the log.

Upvotes: 2

Related Questions