Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a synthesized property already alloc/init -ed?

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?

like image 533
cannyboy Avatar asked Aug 15 '10 17:08

cannyboy


2 Answers

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;
}
like image 115
Seamus Campbell Avatar answered Nov 16 '22 02:11

Seamus Campbell


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.

like image 39
Dave DeLong Avatar answered Nov 16 '22 03:11

Dave DeLong