cannyboy
cannyboy

Reputation: 24426

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?

Upvotes: 7

Views: 3080

Answers (3)

Seamus Campbell
Seamus Campbell

Reputation: 17906

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;
}

Upvotes: 9

tc.
tc.

Reputation: 33592

  • @property only declares the getter/setter methods.
  • @synthesize only generates the accessors for you.

They are not automatically assigned values, apart from the memory being zeroed. Additionally, you have to set them to nil in -dealloc to avoid a leak.

It also doesn't make sense to "alloc a property". An object property is a pointer. (And think of what happens if you have a linked list class...)

(N.B.: The property attributes also affect the @synthesized method, and the properties are also known to the runtime; see class_copyPropertyList() and friends.)

Upvotes: 1

Dave DeLong
Dave DeLong

Reputation: 243146

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.

Upvotes: 7

Related Questions