Writing an NSData Array for a File

I am trying to save an array of images in a documents folder. I managed to save the image as NSData and get it using the method below, but saving the array seems to be outside of me. I have considered several other issues that are related, and it seems that I'm doing everything right.

Adding an image as NSData and saving the image:

[imgsData addObject:UIImageJPEGRepresentation(img, 1.0)]; [imgsData writeToFile:dataFilePath atomically:YES]; 

Receiving data:

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"imgs.dat"]; [self setDataFilePath:path]; NSFileManager *fileManager = [NSFileManager defaultManager]; if([fileManager fileExistsAtPath:dataFilePath]) imgsData = [[NSMutableArray alloc] initWithContentsOfFile:dataFilePath]; 

So, writing an image as NSData using the above works, but not an array of images as NSData. It takes an array, but has 0 objects, which is wrong, since the array that I save has several. Does anyone have any idea?

+6
objective-c iphone
source share
1 answer

First of all, you should clear Cocoa Memory Management , the first line of code is a little worrying.

You may need to go to NSPropertyListSerialization to serialize the data. This class serializes arrays, dictionaries, strings, dates, numbers, and data objects. Unlike initWithContentsOfFile: methods initWithContentsOfFile: it has an error reporting system. Method names and arguments are slightly longer to fit on one line, so sometimes you can see them written using the notation of the eastern Polish Christmas tree . To save the imgsData object, you can use:

 NSString *errString; NSData *serialized = [NSPropertyListSerialization dataFromPropertyList:imgsData format:NSPropertyListBinaryFormat_v1_0 errorDescription:&errString]; [serialized writeToFile:dataFilePath atomically:YES]; if (errString) { NSLog(@"%@" errString); [errString release]; // exception to the rules } 

To read it, use

 NSString *errString; NSData *serialized = [NSData dataWithContentsOfFile:dataFilePath]; // we provide NULL for format because we really don't care what format it is. // or, if you do, provide the address of an NSPropertyListFormat type. imgsData = [NSPropertyListSerialization propertyListFromData:serialized mutabilityOption:NSPropertyListMutableContainers format:NULL errorDescription:&errString]; if (errString) { NSLog(@"%@" errString); [errString release]; // exception to the rules } 

Check the contents of errString to determine what went wrong. Keep in mind that these two methods are deprecated in favor of the dataWithPropertyList:format:options:error: and propertyListWithData:options:format:error: methods, but they were added on Mac OS X 10.6 (I'm not sure if they are available on iOS) .

+8
source share

All Articles