Should IBOutlets be ivars or properties?

前端 未结 2 2032
情书的邮戳
情书的邮戳 2021-02-06 09:24

Though I\'m sure they exists, I\'m having difficulties finding or pinning down an official best practice for declaring outlets in a ViewController.

There are 3 options s

2条回答
  •  情话喂你
    2021-02-06 09:45

    As a rule of thumb, I usually create accessors for IBOutlets.

    In ARC or non-ARC projects I usually do the following:

    //.h (ARC)
    @property (nonatomic, weak) IBOutlet UILabel* myLabel;
    
    //.h (non-ARC)
    @property (nonatomic, retain) IBOutlet UILabel* myLabel;
    
    //.m
    @synthesize myLabel;
    

    In this manner you can let the compiler to create an instance variable for you. But you can also declare your instance variable and tell the compiler to use that.

    Then you can use that accessors/instance variable wherever you want.

    The Apple Memory Management guide says that you have to avoid accessors methods in init or dealloc methods when you have non-ARC projects. So, for example:

    // (non-ARC)
    - (void)dealloc
    {
       [myLabel release]; myLabel = nil; // I'm using the instance variable here!
       [super dealloc];       
    }
    

    This is very important in non-ARC projects. The reason is that, if there is no accessor, KVC will assign the nib object to the instance variable and will put a retain on it. If you forget to release it, you could have a memory leak. Using an accessor force you to release that object at the end.

    I strongly suggest to read friday-qa-2012-04-13-nib-memory-management by Mike Ash. It's a very cool article on nib and memory management.

    Hope it helps.

提交回复
热议问题