objective c - iOS: update object of NSMutableArray in for loop -


i need update / add key -> value pair in nsmutablearray.

i add key fix value if key isn't set already.

i tried following - app crashing @ addobject "mutating method sent immutable object" error:

    nsuserdefaults *defaults = [nsuserdefaults standarduserdefaults];     nsmutablearray *bookmarks = [defaults mutablearrayvalueforkey:@"bookmarks"];      (id bookmark in bookmarks) {          if ([bookmark objectforkey:@"type"] == null){             [bookmark addobject:@"old" forkey:@"type"];         }     }      [[nsuserdefaults standarduserdefaults] synchronize]; 

try this:

nsuserdefaults *defaults = [nsuserdefaults standarduserdefaults];  //saving  nsmutablearray *bookmarkssaving = [nsmutablearray new];  [bookmarkssaving addobject:[[nsmutabledictionary alloc] initwithobjects:@[@"red"] forkeys:@[@"color"]]]; [bookmarkssaving addobject:[[nsmutabledictionary alloc] initwithobjects:@[@"yellow"] forkeys:@[@"color"]]]; [bookmarkssaving addobject:[[nsmutabledictionary alloc] initwithobjects:@[@"green",@"new"] forkeys:@[@"color",@"type"]]];  [defaults setobject:bookmarkssaving forkey:@"bookmarks"]; [[nsuserdefaults standarduserdefaults] synchronize];  //modify  nsmutablearray *bookmarks = [defaults mutablearrayvalueforkey:@"bookmarks"];  nsuinteger index = 0; (nsdictionary *bookmark in bookmarks) {      nsmutabledictionary *bookmarkmutable = [bookmark mutablecopy];      if ([bookmarkmutable objectforkey:@"type"] == nil)     {         [bookmarkmutable setvalue:@"old" forkey:@"type"];         [bookmarks replaceobjectatindex:index withobject:bookmarkmutable];     }      index++; }  [[nsuserdefaults standarduserdefaults] synchronize]; 

you have save bookmarks nsmutabledictionary able add/remove keys/value


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -