Subclassing NSNumber

objective-c

Solution

EDIT: Heed the warnings in comments! This is a good solution for many classes; it may not be good for NSNumber, NSString, and possibly others like NSArray etc. because they do behind-the-scenes magic for performance reasons that may lead to unexpected behavior, like sharing instances.

How about saving yourself the pain of subclassing, and instead extending the class with a category?

Have a look here: http://oleb.net/blog/2011/05/faking-ivars-in-objc-categories-with-associative-references/

Problem

I want to add a property to an NSNumber class, so I have to subclass it. The documentation states that I then have to override all NSValue primitive methods. Since the NSValue documentation does not state which methods are the primitive ones, I figured that these two are probably the primitive ones for instantiation: ``` – initWithBytes:objCType: + valueWithBytes:objCType: ``` So I made my class as: ``` @interface MultipleNumber : NSNumber { NSNumber *_number; } @property (nonatomic, getter = isMultiple) BOOL multiple; @end @implementation MultipleNumber @synthesize multiple=_multiple; -(id)initWithBytes:(const void *)value objCType:(const char *)type { self = [super init]; if (self) { _number=[[NSNumber alloc] initWithBytes:value objCType:type]; } return self; } +(NSValue *)valueWithBytes:(const void *)value objCType:(const char *)type { return [[[MultipleNumber alloc] initWithBytes:value objCType:type] autorelease]; } -(void)getValue:(void *)value { [_number getValue:value]; } -(const char *)objCType { return [_number objCType]; } @end ``` But when I call[NSNumber numberWithBool:YES], I still get a _NSCFBoolean class back and the "primitive methods" are not called. How can I figure out what methods are considered primitive?

Original source

Related problems