Using alloc in objective c for my own classes
-
02-07-2021 - |
Question
When I use alloc
on a class that I created (for example on stack class that has an underlying NSMutableArray
object) will it apply alloc to all of the properties of it ? or do I have to override the alloc
method to make sure that the alloc
is called on properties ?
Solution
You do not need to override the alloc method, the properties will be initialized for you to their default values, that is nil for objects and the default values for the primitive types.
So all you need to do:
[[myObject alloc] init]; or the shortcut [myObject new];
You cannot override the alloc method, all the properties will just be set to their default values. You can however override init, to set initial values to properties (instead of their default values):
- (id) init {
self = [super init];
if (self) {
//initialize some properties
}
return self;
}
OTHER TIPS
All of the properties won't be alloced for you.
However, don't override alloc for that, override init to alloc and init the properties.
In general, the properties won't be alloced for you. However the ones that you add in IB and set as outlets will automatically be created.