objective c - NSMutableArray overwrites last object -


i had initialized both nsmutablearray , nsmutable dictinay outside loop overwriting last object array

nsmutabledictionary *dictnew=[[nsmutabledictionary alloc]init]; nsmutablearray *newarr =[[nsmutablearray alloc]init]; //dictnew=[[nsmutabledictionary alloc]init];  (int i=0; i<[[[contactsdata valueforkey:@"firstname"] objectatindex:0] count]; i++) {     [dictnew setobject:[[[contactsdata valueforkey:@"firstname"]objectatindex:0]objectatindex:i] forkey:@"firstname"]:     [dictnew setobject:[[[contactsdata valueforkey:@"lastname"]objectatindex:0]objectatindex:i] forkey:@"lastname"];     [dictnew setobject:[[[contactsdata valueforkey:@"phones"]objectatindex:0]objectatindex:i] forkey:@"phones"];     nslog(@"%@",dictnew);     [newarr addobject:dictnew];     nslog(@"newarr %@",newarr); } 

you can't reuse dictnew that. need new instance each iteration. have it, end adding same dictionary array on , over.

try this:

nsmutablearray *newarr = [[nsmutablearray alloc]init]; (int = 0; < [[[contactsdata valueforkey:@"firstname"] objectatindex:0] count]; i++) {     nsmutabledictionary *dictnew=[[nsmutabledictionary alloc]init];     [dictnew setobject:[[[contactsdata valueforkey:@"firstname"]objectatindex:0]objectatindex:i] forkey:@"firstname"]:     [dictnew setobject:[[[contactsdata valueforkey:@"lastname"]objectatindex:0]objectatindex:i] forkey:@"lastname"];     [dictnew setobject:[[[contactsdata valueforkey:@"phones"]objectatindex:0]objectatindex:i] forkey:@"phones"];     nslog(@"%@",dictnew);     [newarr addobject:dictnew];     nslog(@"newarr %@",newarr); } 

i suggest minor improvements , cleanup:

nsmutablearray *newarr = [[nsmutablearray alloc] init]; nsarray *firstnames = [[contactsdata valueforkey:@"firstname"] objectatindex:0]; (nsinteger = 0; < firstnames.count; i++) {     nsmutabledictionary *dictnew = [[nsmutabledictionary alloc] init];     dictnew[@"firstname"] = firstnames[i];     dictnew[@"lastname"] = [[[contactsdata valueforkey:@"lastname"] objectatindex:0] objectatindex:i];     dictnew[@"phones"] = [[[contactsdata valueforkey:@"phones"] objectatindex:0] objectatindex:i];     nslog(@"dictnew = %@", dictnew);     [newarr addobject:dictnew]; } nslog(@"newarr = %@", newarr); 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -