0
내 사용자 지정 개체를 보관하고 싶습니다. ClassA는 값이 ClassB의 인스턴스 인 사전을 보유합니다.NSCoding 및 ARC
모든 것이 ClassA의 initWithCoder처럼 보이고 _dictionary는 strong
으로 선언되지만, init 반환 후 callMeAfterInit
을 호출하면 _dictionary가 비어 있습니다 (null이 아닌 유효한 빈 사전).
이것은 간단해야하지만 많은 것을 보관하지 않았기 때문에 기본 사항이 누락되었습니다. init이 리턴 한 후 사전을 비우는 원인은 무엇입니까?
여기에 필수 코드입니다 :
@interface ClassA : NSObject <NSCoding>
@property (strong, nonatomic) NSMutableDictionary *dictionary;
@end
@implementation ClassA
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.dictionary forKey:@"dictionary"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self) {
_dictionary = [decoder decodeObjectForKey:@"dictionary"];
// breakpoint here and I can inspect a good dictionary, full of ClassB values
}
return self;
}
- (void)callMeAfterInit {
NSLog(@"%@", self.dictionary);
// Log output here shows an empty dictionary (valid, but with 0 pairs)
}
@end
@interface ClassB : NSObject <NSCoding>
@property (strong, nonatomic) NSNumber *number;
@property (strong, nonatomic) NSArray *array;
@end
@implementation ClassB
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.number forKey:@"number"];
[encoder encodeObject:self.array forKey:@"array"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self) {
_number = [decoder decodeObjectForKey:@"number"];
_array = [decoder decodeObjectForKey:@"array"];
}
return self;
}
@end
오류를 찾는데 도움이되었으므로이 부분을 올바르게 표시하겠습니다. 질문과 무관하게, 나는 초기화 후에 사전을 비운 라인을 발견했다. 단 하나의 인스턴스가 있지만,이 대답에서 알 수 있듯이 추가 인스턴스를 찾는 것은 저의 실수를 발견하게합니다. 그래서 실제 정답은 내가 바보입니다. (아카이브 자료는 내가 생각한만큼 충분히 새것이다.) 도와 주셔서 감사합니다! – danh