0
對象我有一個類A
和子類B
:存檔/取消存檔父子用鑰匙
@interface A:NSObject<NSCoding>
String a;
String b;
@end
@interface B: A<NSCoding>
int c;
// `a` and `b` attributes are inherited
@end;
我要存檔的A
一些對象,並使用屬性a
作爲key
一些B
。 在兩個類中的encoding
和decoding
協議已經被定義爲:
@implementation A
...
- (void) encodeWithCoder:(NSCoder *)encoder {
//[super encodeWithCoder:encoder];
[encoder encodeObject:self forKey:a];
}
- (id)initWithCoder:(NSCoder *)decoder {
// self = [super initWithCoder:decoder];
if (self=[super init]) {
self = [decoder decodeObjectForKey:a];
}
return self;
}
@end
@implementation B
..
- (void) encodeWithCoder:(NSCoder *)encoder {
[super encodeWithCoder:encoder];
[encoder encodeObject:self forKey:super.a];
}
- (id)initWithCoder:(NSCoder *)decoder {
//self = [super initWithCoder:decoder];
if (self) {
self = [decoder decodeObjectForKey:super.a];
}
return self;
}
對於一些對象列表dataArray = [A("One"), B("Two")]
,歸檔邏輯是
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dataArray];
NSError* error = nil;
BOOL success = [data writeToFile: @"xyz.dat" options:0 error: &error];
if (!success)
NSLog(@"error = %@", [error description]);
再從歸檔數據讀取:
NSData *lD = [[NSData alloc] initWithContentsOfFile:@"xyz.dat"];
NSKeyedUnarchiver *arc = [[NSKeyedUnarchiver alloc] initForReadingWithData:lD];
現在將屬性爲a
的對象設置爲"One"
在嘗試從歸檔數據中讀取對象時,我得到了null
!
NSLog(@"Value - %@",[arc decodeObjectForKey:@"One"]);
檢查該鏈接的http://計算器。 COM /問題/ 41116832 /時,歸檔對象中最FUNC-encodewith-acoder-nscoder-方法 - 崩潰,使用/ 41116908#41116908 –