Is a synthesized property already alloc/init -ed?

后端 未结 3 1834
旧巷少年郎
旧巷少年郎 2021-01-02 17:19

If I have a custom NSObject class called ProgramModel, does it get alloc/init -ed when I @property and @synthesize it from another cla

相关标签:
3条回答
  • 2021-01-02 17:57
    • @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.)

    0 讨论(0)
  • 2021-01-02 18:00

    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;
    }
    
    0 讨论(0)
  • 2021-01-02 18:10

    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.

    0 讨论(0)
提交回复
热议问题