When you have one object as a property of another object in Objective-C, does it automatically initialize when you use @synthesize
?

- 63,694
- 13
- 151
- 195

- 255
- 1
- 4
- 12
-
your object should be stored as a pointer, which will be initialised to `nil` – Dave Aug 11 '13 at 19:35
4 Answers
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.
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.

- 18,392
- 8
- 66
- 81
No. The @synthesize does not know how to initialize it. Simple -init
?
You can allocate and initialize it in the -init…
of the referring object.

- 16,582
- 3
- 35
- 50
You still have to init. Try using lazy initialization:
-(MyPropertyClass*)propertyName {
if(!propertyIvarName) {
_propertyIvarName = [[MyPropertyClass alloc] init];
}
return propertyIvarName;
}
or init the property in viewdidload

- 6,878
- 8
- 35
- 70
-
This pattern is dangerous in some scenarios, because the property can never be set to nil. – Amin Negm-Awad Aug 11 '13 at 19:40
-
1This can also lead to problems, if the property is called from multiple threads. – Marcelo Aug 11 '13 at 19:41
-
3