roomorama / RMMapper

Other
208 stars 42 forks source link

Extending an existing object: adding a new property #8

Closed naartjie closed 10 years ago

naartjie commented 10 years ago

I'm not sure if this is a bug, or if I'm just using this library wrong. I'm using version 1.1.1 (installed via CocoaPods).

I need to add a property to one of my objects:

@interface Points : NSObject
@property NSInteger existing;
@property NSInteger newProperty;
@end

The problem is when I run this on a device which has an old version serialised. This line throws an exception when I try to read the object:

_points = [_userDefaults rm_customObjectForKey:@"points"];

I can think of some hacky workarounds, but is there an elegant way of doing this? Ideally to specify a default value for newProperty if one isn't found in NSData from NSDefaults.

thomasdao commented 10 years ago

Oh I know why, your property cannot be NSInteger, let's try with NSNumber instead. The reason is setValue:forKey: method only works with NSObject type but doesn't work on primitive type like int, NSInteger. I will update documentation for this issue.

Sent from my iPhone

On 25 Apr, 2014, at 7:02 pm, Marcin Jekot notifications@github.com wrote:

I'm not sure if this is a bug, or if I'm just using this library wrong. I'm using version 1.1.1 (installed via CocoaPods).

I need to add a property to one of my objects:

@interface Points : NSObject @property NSInteger existing; @property NSInteger newProperty; @end The problem is when I run this on a device which has an old version serialised. This line throws an exception when I try to read the object:

_points = [_userDefaults rm_customObjectForKey:@"points"]; I can think of some hacky workarounds, but is there an elegant way of doing this? Ideally to specify a default value for newProperty if one isn't found in NSData from NSDefaults.

— Reply to this email directly or view it on GitHub.

naartjie commented 10 years ago

Great, that works, thanks. So now I have:

@interface Points : NSObject
@property NSInteger existing;
@property (nonatomic, retain) NSNumber* newProperty;
@end

@implementation Points
- (NSNumber *)newProperty {
    return _newProperty ? _newProperty : [NSNumber numberWithInt:0];
}
@end

The getter is to deal with the initial case, where newProperty is null, and I'm defaulting it to 0

Edit: I changed the return value to [NSNumber numberWithInt:0]