2010-09-29 130 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