0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.