user616076
user616076

Reputation: 4001

Problems adding data to a plist file

I've been trying to write data back to a pre-defined plist file (data.plist) in my bundle. Using the code below I call the routine 'dictionaryFromPlist' to open the file and then call 'writeDictionaryToPlist' to write to the plist file. However, no data gets added to the plist file.

NSDictionary *dict = [self dictionaryFromPlist];

NSString *key = @"Reports";
NSString *value = @"TestingTesting";
[dict setValue:value forKey:key];

[self writeDictionaryToPlist:dict];


- (NSMutableDictionary*)dictionaryFromPlist {
  NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
  NSMutableDictionary* propertyListValues = [[NSMutableDictionary alloc]      
  initWithContentsOfFile:filePath];
  return [propertyListValues autorelease];
}

- (BOOL)writeDictionaryToPlist:(NSDictionary*)plistDict{
  NSString *filePath = @"data.plist";
  BOOL result = [plistDict writeToFile:filePath atomically:YES];
  return result;
}

The code runs through successfully and no error is thrown but no data is added to my plist file.

Upvotes: 2

Views: 1246

Answers (2)

Mat
Mat

Reputation: 7633

As mentioned by @logancautrell you can not write in mainbundle, you can save your plist in the app documents folder, you could do so:

 NSString *path = @"example.plist";
 NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *basePath = ([paths count]> 0)? [paths objectAtIndex: 0]: nil;
 NSString *documentPath = [basePath stringByAppendingPathComponent:path] // Documents
 NSFileManager *fileManager  = [NSFileManager defaultManager];
 BOOL checkfile = [fileManager fileExistsAtPath: documentPath];
 NSLog(@"%@", (checkFile ? @"Exist": @"Not exist"));//check if exist
 if(!checkfile) {//if not exist
    BOOL copyFileToDoc = [yourDictionary writeToFile:documentPath atomically: YES];
    NSLog(@"%@",(copyFileToDoc ? @"Copied": @"Not copied"));
  }

Upvotes: 1

logancautrell
logancautrell

Reputation: 8772

You can not write to your bundle, it is read only. If your case though, you are writing to a relative path, not to the bundle.

I'm not sure what the default working directory is for iOS apps. It is best to use absolute paths. You should be writing to the documents/cache directory. Something like this will get the path for you:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

Then just grab the lastObject and prepend that to your file name.

Upvotes: 2

Related Questions