简体   繁体   中英

Not able to write to Plist

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.

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];

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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM