Objective C Object Creation
I'm learning Objective C for a native OSX project that I'm working on. Here are some quick notes about creating objects.
The way that I don't prefer
The first way is to call two
This best way is to nest them so that you can be sure you're calling the
method on the newly allocated object.
CustomObject *customObject = [[CustomObject alloc] init];
Some Objects accept a variation on the
- (id)initWithBool:(BOOL)value; - (id)initWithFloat:(float)value; - (id)initWithInt:(int)value; - (id)initWithLong:(long)value; CustomObject *customObject = [[CustomObject alloc] initWithBool:YES];
However that seems really nasty to me. Thankfully there is a shortcut
NSObject which is better suited to my tastes.
CustomObject *customObject = [CustomObject new];
The way that I prefer
Some Objects have factory methods which I much prefer. They allow you to both allocate memory for an Object as well as initialize it with variables.
NSNumber is a good example.
+ (NSNumber *)numberWithBool:(BOOL)value; + (NSNumber *)numberWithFloat:(float)value; + (NSNumber *)numberWithInt:(int)value; + (NSNumber *)numberWithLong:(long)value; NSNumber *myNum = [NSNumber numberWithInt:32];
This accomplishes the same think as nesting the
messages but is much more readable.
See something wrong or got something to add/change? Fork this git repo and send me a pull request
If you particularly enjoy my work, I appreciate donations given with Gitcoin.co