2010-09-29 126 views
6

我试图将一个图像数组保存到文档文件夹。我设法将图像保存为NSData,并使用下面的方法进行检索,但保存数组似乎超出了我的想象。我看过其他几个相关的问题,看起来我做的都是对的。将一个NSData数组写入文件

添加图像的NSData和保存图像:

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

检索数据:

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]; 

因此,在使用上述作品写入图像作为NSData的,而不是像阵列作为NSData。它在数组中,但它有0个对象,这是不正确的,因为我保存的数组有几个。有没有人有任何想法?

回答

8

首先,你应该刷一下Cocoa Memory Management,第一行代码有点担心。

对于数据序列化,您可能喜欢NSPropertyListSerialization。这个类串行化数组,字典,字符串,日期,数字和数据对象。它有一个错误报告系统,不像initWithContentsOfFile:方法。方法名称和参数有点长,以适合一行,所以有时您可能会看到它们用Eastern Polish Christmas Tree表示法写入。为了节省您的imgsData对象,你可以使用:

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 
} 

要回读它,使用errString

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 
} 

检查的内容来确定什么地方出了错。请记住,这两种方法已被弃用,以支持dataWithPropertyList:format:options:error:propertyListWithData:options:format:error:方法,但是这些方法是在Mac OS X 10.6中添加的(我不确定它们是否可用于iOS)。

+0

关于内存管理的好处。 +1 – Moshe 2010-09-29 04:05:42

+0

哇,完美!谢谢,它创造奇迹! – Beaker 2010-09-29 05:30:31

+0

另外,在附注中,dataWithPropertyList:format:options:error:在iOS 4中可用。所以对我来说不是很有用,但可以帮助任何iPhone 4程序员。 – Beaker 2010-09-29 05:33:50