I’m trying to save an array to a .plist file on my iphone but it won’t save to it. When i try it on the simulator it works. But when i run it on the iphone it doesn’t work. I check if the file exists on the device and it does and i can read the data from the file, but it won’t write to it. Here is the code when i add the data to the .plist file.
//Sorts the arrays
[self sortArrays];
NSString *sString = [[NSString alloc] initWithFormat:@"Schema%i", currentIndex];
NSString *daPath = [[NSBundle mainBu开发者_高级运维ndle] pathForResource:sString ofType:@"plist"];
NSLog(@"Path: %@", daPath);
//Checks if the file exists
BOOL exists;
NSFileManager *fileManager = [NSFileManager defaultManager];
exists = [fileManager fileExistsAtPath:daPath];
if(!exists)
NSLog(@"PATH %@ DOES NOT EXIST", daPath);
else
NSLog(@"PATH %@ DO EXIST!!", daPath);
//Writes out the array to check if it gots any elements
for (int i = 0; i < [itemsArray count]; i++)
NSLog(@"%i: %@", i, [(NSMutableArray*)[itemsArray objectAtIndex:i] objectAtIndex:0]);
//Writes the array to the .plist
[itemsArray writeToFile:daPath atomically:YES];
//Gets the .plist file
NSMutableArray *tmpA2 = [[NSMutableArray alloc] initWithContentsOfFile:daPath];
//Checks if the new elements that got added is there.
for (int i = 0; i < [tmpA2 count]; i++)
NSLog(@"FILE: %i: %@", i, [(NSMutableArray*)[tmpA2 objectAtIndex:i] objectAtIndex:0]);
[sString release];
[itemsArray release];
sString = nil;
itemsArray = nil;
Does anyone know why it doesn’t work?
You can not write into the app bundle, you need to write to the app's document directory.
NSString *fileName = @"fileName";
NSArray *searchPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = [searchPath objectAtIndex:0];
NSString *filePath = [documentDirectoryPath stringByAppendingPathComponent:fileName];
If there is initial data in a file in the app bundle on startup copy it to the document directory if it does not exist and then it can be read, modified and written..
精彩评论