initWithCoder: calling init in custom class
initWithCoder: calling init in custom class
- Subject: initWithCoder: calling init in custom class
- From: Trygve Inda <email@hidden>
- Date: Mon, 16 Jun 2014 13:36:01 -0700
- Thread-topic: initWithCoder: calling init in custom class
I have a custom class:
@interface MyClass : NSObject {}
@property (nonatomic, retain) NSNumber* valueA;
@property (nonatomic, retain) NSNumber* valueB;
@property (nonatomic, retain) NSNumber* valueC;
@end
@implementation MyClass
-(id)init
{
if (self = [super init])
{
[self valueA:[NSNumber numberWithInteger:3]];
[self valueB:[NSNumber numberWithInteger:6]];
[self valueC:[NSNumber numberWithInteger:9]];
}
return self;
}
I am wondering how to handle NSCoding in such a way that if I encode and
save to disk a MYClass object, but then latter add other instance variables
to the class, that the object still gets correctly initialized for values
that are not being decoded.
-(id)initWithCoder:(NSCoder *)coder
{
if (self = [super init])
{
self.valueA = [coder decodeObjectForKey:kValueAKey];
self.valueB = [coder decodeObjectForKey:kValueBKey];
self.valueC = [coder decodeObjectForKey:kValueCKey];
}
}
Or should I call:
-(id)initWithCoder:(NSCoder *)coder
{
if (self = [self init])
{
self.valueA = [coder decodeObjectForKey:kValueAKey];
self.valueB = [coder decodeObjectForKey:kValueBKey];
self.valueC = [coder decodeObjectForKey:kValueCKey];
}
}
In the later method, if the encoded object does not contain kValueCKey, the
object created will still have the correct default value for valueC (9).
In the former method, valueC would be nil.
Thoughts?
Thanks,
Trygve
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden