简体   繁体   中英

Not able to save data into Plist?

HI i have a NSMutableDictionary and i added 5 objects with keys (latitude, longitude, intensity, image, metaimage) then I tried to add it into a NSMutableArray and write that NSMutableArray to a .plist file. But Actually it is not writing. My .plist file is still empty.

Please check my code:

paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"history.plist"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];

if([latitude length]>0 && [longitude length]>0){
[dictValue setObject:latitude forKey:@"latitude"];
[dictValue setObject:longitude forKey:@"longitude"];
}
[dictValue setObject:metaImage forKey:@"imageData"];
[dictValue setObject:image forKey:@"image"];
if([_intensity.text length]>0){
[dictValue setObject:_intensity.text forKey:@"intensity"];
}else{
    intensityAlert=[[UIAlertView alloc]initWithTitle:@"Beta App" message:@"Please select intensity." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [intensityAlert show];
}

if(fileExists){
    finalArray=[[NSMutableArray alloc]initWithContentsOfFile:filePath];
    [finalArray addObject:dictValue];
    NSLog(@"dd%@",dictValue);

}else{
    [finalArray addObject:dictValue];
    NSLog(@"new%@",finalArray);

}
[finalArray writeToFile:filePath atomically:YES];

after that i use following code to check the data inside plist

   finalArray=[[NSMutableArray alloc]initWithContentsOfFile:filePath];
    NSLog(@"server%@",finalArray);

It printing nil value.

Let's try:

  1. finalArray is allocated in else:

     if(fileExists){ finalArray=[[NSMutableArray alloc]initWithContentsOfFile:filePath]; [finalArray addObject:dictValue]; NSLog(@"dd%@",dictValue); }else{ // let be sure that final array allocated : [[NSMutableArray alloc] initWith...] [finalArray addObject:dictValue]; NSLog(@"new%@",finalArray); } 
  2. metaImage or image must be saved by NSData format

Hope this helps you.

As Document for - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag :

This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

You can try save image into a folder , and save the image relative file path to plist file.

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