Search code examples
iosobjective-cplist

Data not saving to property list - iOS


I have followed a number of tutorials, googled the problem and cannot understand why I am unable to save data to a property list

throughout my research I was able to determine that 'writeToFile' is returning 0, this can be due to custom data types (classes) yet all I am attempting to save is a NSNumber which is compatible with a property list.

Please help, as I cannot work out why this will not save, I am testing in the IPhone Simulator, no file is being created in the ~/Documents folder

Regards

- (void)saveData{

    NSLog(@"*** SAVING DATA ***");
    DataManager *datamgr = [DataManager sharedManager];

    NSString *error;

    //get path of data plist in users Document directory
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *plistPath = [rootPath stringByAppendingPathComponent:@"Data.plist"];

    NSNumber *gems = [NSNumber numberWithInt:datamgr.gemCount];

    //create arrays for data and keys
    NSArray *data = [NSArray arrayWithObjects:gems, nil];
    NSArray *keys = [NSArray arrayWithObjects:@"Gems", nil];

    //create dictionary with data against keys
    NSDictionary *plistDict = [NSDictionary dictionaryWithObjects:data forKeys:keys];

    NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict
                                                               format:NSPropertyListXMLFormat_v1_0
                                                     errorDescription:&error];

    //write file from dictionary
    if(plistData) {
        if([plistData writeToFile:plistPath atomically:YES] != 0){
            NSLog(@"write file to plist");
        }
    }
    else {
        NSLog(@"%@",error);
    }
}

Solution

  • Only thing I can see wrong is what directories you are searching. Try changing:

    //get path of data plist in users Document directory
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    

    To this:

    //get path of data plist in users Document directory
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    

    I'd also suggest debugging on a physical device, the simulator is ok but it does have its own share of issues in some cases.