1

I have problem with adding and removing items in an array inside a plist file in XCODE.

I'm able to read the array by following code:

// Path to the plist (in the application bundle) ------>>>>>
NSString *path = [[NSBundle mainBundle] pathForResource:
                  @"Fav" ofType:@"plist"];

// Build the array from the plist  ------>>>

NSDictionary *favs = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
Resepies = [favs objectForKey:@"Root"];

And this my plist structure

enter image description here

The senario is to let the user add and remove specific item from the array at a time.

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
danialmoghaddam
  • 343
  • 1
  • 6
  • 21
  • possible duplicate of [Can i modify Root.plist in settings bundle dynamically?](http://stackoverflow.com/questions/6941272/can-i-modify-root-plist-in-settings-bundle-dynamically) – Parag Bafna Jun 12 '12 at 11:07

2 Answers2

3

try this code -

NSString *path = [[NSBundle mainBundle] pathForResource: @"Fav" ofType:@"plist"];

// Build the array from the plist  ------>>>

NSDictionary *favs = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

Resepies = [favs objectForKey:@"Root"];

[Resepies addObject:addYourObjectHere];

//then add this array into dictonary ; 

[favs setObject:Resepies forKey:@"Root"];

// now write dictionary to plist

[favs writeToFile:yourPlistName atomically:YES];
TheTiger
  • 13,264
  • 3
  • 57
  • 82
Abhishek
  • 2,255
  • 1
  • 13
  • 21
2

You can't modify files in the application bundle, which is what your code above is attempting to do.

If the file is supposed to be modifiable, you need to move it into the documents folder first (say, on first run) and then read / write to that one subsequently. There are plenty of questions dealing with how to do this, for example : create plist and copying plist to document directory

Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132