Reputation: 1792
Sorry if the title is confused but I can't find a way to express my question.
I see many Objective-C example codes and they usually use this:
Clazz *clazz = [[Clazz alloc] init];
self.clazz = clazz;
instead of:
self.clazz = [[Clazz alloc] init];
Does the first approach have any advantage over the second one?
Upvotes: 3
Views: 74
Reputation: 2398
This is usually just a stylistic preference. It's possible that you want to declare Class *clazz = [[Clazz alloc] init];
in a separate line so that you call methods on it, or set properties on the class, before you actually assign it to the property, especially if you have a custom setter for that class.
eg:
@interface ThisIsAClass ()
@property (nonatomic, strong) Clazz *clazz;
@end
@implementation ThisIsAClass
- (instancetype) init {
if (self = [super init]) {
Clazz *clazz = [[Clazz alloc] init];
clazz.widgets = @[@"onesie", @"twosie"];
self.clazz = clazz;
}
return self;
}
- (void)clazz:(Clazz *)newClazz {
// Make sure we're assigning valid values to this property
NSAssert(newClazz.widgets.count > 0, @"Widgets count must be > 0!");
_clazz = newClazz;
}
@end
Upvotes: 2
Reputation: 385720
There's no advantage if that's all it does. If the code uses clazz
further, then accessing a local variable saves the nanoseconds required to call the self.clazz
getter, and avoids the getter entirely which could matter if the getter does anything weird.
Upvotes: 5