If I have a custom NSObject
class called ProgramModel, does it get alloc/init -ed when I @property
and @synthesize
it from another class?
For instance, in a ProgramController class like this
// ProgramController.h
#import "ProgramModel.h"
@interface ProgramController : UIViewController {
ProgramModel *programModel;
}
@property (nonatomic, retain) ProgramModel *programModel;
// ProgramController.m
#import "ProgramController.h"
@implementation ProgramController
@synthesize programModel;
// etc
Do I also need to alloc/init in the initWithNibName
or viewDidLoad
, or is it already alloc/init
-ed because of the property/synthesize
?
You need to populate the property manually. The exception is if you have an IBOutlet property
that you've connected in a nib file; that will get populated automatically when the nib is loaded.
I find that for view controllers the vast majority of properties are IBOutlets
and properties that describe what the view will show, and the latter case is usually set by the object that creates the view controller. That will usually be the case for a view controller that shows a detail view for some object.
If you do have properties that are completely local to the view controller, a common pattern is to write your own getter and setter (rather than using @synthesize
) and create the object in the getter if it doesn't exist. This lazy-loading behavior means you can easily free up resources in low-memory conditions, and that you only pay the cost of loading an object when you need it.
// simple lazy-loading getter
-(MyPropertyClass*)propertyName {
if(propertyIvarName == nil) {
propertyIvarName = [[MyPropertyClass alloc] init];
// ... other setup here
}
return propertyIvarName;
}
By default, all instance variables are zero'd out. In the case of objects, that means they're nil
. If you want an initial value in the property, you need to put it there during your initializer/viewDidLoad
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With