When you have one object as a property of another object in Objective-C, does it automatically initialize when you use @synthesize?
Does an object initialize automatically if it is the synthesized property of another object?
1k views Asked by Horton Jackson At
4
There are 4 answers
0
On
does it automatically initialize when you use
@synthesize?
Yes, it is initialized to nil (no actual object is allocated, however - this is pointer initialization in the C sense of the word, the init method is not called).
By the way, you don't even have to @synthesize to achieve this behavior - every instance variable, even those which don't have a corresponding @property, are automatically initialized either to nil (in case of objects), NULL (in case of other pointers) or 0 (in case of integers and floating-point numbers) by the Objective-C runtime.
0
On
Let's try it:
@interface TypicalObject : NSObject
@property (nonatomic) NSNumber *numberProperty;
@end
@implementation TypicalObject
@synthesize numberProperty;
@end
...
TypicalObject *object = [[TypicalObject alloc] init];
NSLog(@"object.numberProperty = %@", object.numberProperty);
The log statement yields:
object.numberProperty = (null)
So, no, properties do not auto-instantiate. All object instance variables begin as nil, however.
You still have to init. Try using lazy initialization:
or init the property in
viewdidload