所以我有一個對象,我已經實現NS編碼。我一整天都在用我的腦子一直在痛苦。根據我的理解,因爲我已經實現了NSCoding,所以在數組本身調用存檔/解除存檔方法時,應該對數組的索引進行編碼和解碼。所以無論我對它是如何工作的理解都是關閉的,或者我的實現有一些錯誤。iOS序列化/反序列化不能正常工作
該文件被寫入,並且陣列被反序列化,並將其顯示在它的對象。但是數組中的類沒有數據。
實施看起來是這樣的:
#pragma mark NSCoding
#define kTitle @"Title"
#define kDescription @"Description"
#define kIsCompleted @"IsCompleted"
#define kDate @"Date"
#define kImage @"Image"
-(id)initWithCoder:(NSCoder *)decoder
{
[super init];
title = [decoder decodeObjectForKey:kTitle];
description = [decoder decodeObjectForKey:kDescription];
isCompleted = [decoder decodeBoolForKey:kIsCompleted];
date = [decoder decodeObjectForKey:kDate];
image = [decoder decodeObjectForKey:kImage];
return self;
}
-(void) encodeWithCoder:(NSCoder *) encoder
{
[encoder encodeObject:title forKey:kTitle];
[encoder encodeObject:description forKey:kDescription];
[encoder encodeBool:isCompleted forKey:kIsCompleted];
[encoder encodeObject:date forKey:kDate];
[encoder encodeObject:image forKey:kImage];
}
@end
編碼看起來是這樣的,有」了一些故障排除的變化:
-(void) writeFile
{
NSData *encodedObject;
encodedObject = [NSKeyedArchiver archivedDataWithRootObject: bucketItems];
//NSFileHandle *file;
// file = [NSFileHandle fileHandleForWritingAtPath:filePath];
//if(true)//file == nil)
//{
//NSLog(@"Failed to open a file handle for writing. Attempting to create a file.");
//[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
//file = [NSFileHandle fileHandleForWritingAtPath:filePath];
//if(file == nil)
//{
// NSLog(@"Unable to create new file.");
// }
//}
[encodedObject writeToFile:self.filePath atomically:YES];
//[file writeData: encodedObject];
//[file closeFile];
}
,然後解碼發生在這裏,程序啓動時,檢查如果有保存的數據,並加載它
NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *fileData;
fileData = [file readDataToEndOfFile];
bucketItems = [NSKeyedUnarchiver unarchiveObjectWithData:fileData];
NSLog(@"Data file found: loading");
[file closeFile];
是否調用了initWithCoder? – Rob
啊這是..我沒有檢查,它看起來像場被解碼..現在爲什麼數組沒有看到正確初始化對象 –
所以bucketItems並最終被同一陣列,具有每個項目正確的屬性?聽起來像你做的? (使用記錄斷點它轉儲到控制檯右側是未歸檔後..) – Rob