1

I have a very basic question about how to write to a plist. I added a "Here.plist" file to my resources folder. The following is my code:

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

NSArray *array = [[NSArray alloc]initWithObjects:@"First", @"Second", @"Third", nil];

[array writeToFile:path atomically:YES];

"Here.plist" is still empty after executing the code. I even tried using a NSDictionary as follows:

NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"firstValue", @"First", @"secondValue", @"Second", @"thirdValue", @"Third", nil];

[dict writeToFile:path atomically:YES];

I went through many tutorials and forums but its just not working for me. What am i doing wrong? Losing my head over this.

HG's
  • 818
  • 6
  • 22

2 Answers2

7

You can't write into the bundle. Try writing into the documents directory. For example:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *array = [[NSArray alloc]initWithObjects:@"First", @"Second", @"Third", nil];
[array writeToFile:[documentsDirectory stringByAppendingPathComponent:@"Here.plist" atomically:YES];
fsaint
  • 8,759
  • 3
  • 36
  • 48
  • Hey thanks, that worked. One question though, why don't the values get added to the plist in my resources folder? The values are being added to the /users/name/library/application support... folder. – HG's Feb 25 '11 at 12:59
  • 1
    You can't write into your resources folder. Partly because your complete bundle (including the resources folder) is signed. Any change to the bundle would invalidate the signature and the app would not run. The Documents directory is the place to store files that are created after installation or that will change after installation. Any files in the resources dir needs to be included when packaging the app. That is to saym before the app is signed. – fsaint Feb 25 '11 at 13:05
  • Ohk. Thanks a lot. Was stuck in this problem for so long. – HG's Feb 25 '11 at 13:09
2

I suspect your problem is due to the fact that you can't write to the application bundle, only to your application's document store.

To obtain a path to the document store, use:

NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docStorePath = [searchPaths objectAtIndex:0];

NSString *filePath = [docStorePath stringByAppendingPathComponent:@"XXXXX"];
John Parker
  • 54,048
  • 11
  • 129
  • 129
  • That did the trick. But why doesn't the plist in my project get updated. It got added to the plist in the application support folder. Why's that?? – HG's Feb 25 '11 at 13:01