You don't show the code that calls callMeAfterInit
, so this is a guess.
More likely than not, you aren't talking to the same instance of ClassA
. Did you happen to call [[ClassA alloc] init];
somewhere?
Question
I'd like to archive my custom objects. ClassA holds a dictionary whose values are instances of ClassB.
Everything looks good ClassA's initWithCoder, and _dictionary is declared strong
, but after init returns and I call callMeAfterInit
, the _dictionary is empty (not null, a valid empty dictionary).
This ought to be simple, but I haven't used archiving much, so maybe I'm missing something basic. What might cause the dictionary to be emptied after the init returns?
Here's the essential code:
@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
Solution
You don't show the code that calls callMeAfterInit
, so this is a guess.
More likely than not, you aren't talking to the same instance of ClassA
. Did you happen to call [[ClassA alloc] init];
somewhere?