Should I declare variables in interface or using property in objective-c arc?

前端 未结 2 1967
无人共我
无人共我 2020-11-28 05:04

approach 1:

@interface MyController : UIViewController {
    UILabel *myText;
}

@property (nonatomic, strong) UILabel *myText;

approach 2:

相关标签:
2条回答
  • 2020-11-28 05:09

    You may also want to use @synthesize if you like a nice table of contents of your @synthesized properties that you can refer to and comment for clarity and organization.

    Also, an @synthesize allows you to set a breakpoint on the property and trap when its value is changed.

    When the compiler does everything for you, you end up being distanced from what is really happening and ignorant to it. However, not having to type out everything yourself all the time is also nice.

    0 讨论(0)
  • 2020-11-28 05:22

    The most modern way1:

    • whenever possible, declare properties
    • don't declare iVars separately 2
    • don't @synthesize 3
    • locate as few properties as possible in you .h file 4
    • locate as many properties as possible in a class extension in your .m file 5

    1 As of Xcode 4.5.2. Most of this applies back to 4.4, some of it won't compile on 4.2 (the last version available under Snow Leopard). This is preprocessor stuff, so it is all compatible back at least to iOS5 (I haven't tested on iOS4 but that should also be OK).

    2 There is no point in declaring an iVar as well as a property. I am sure there are a few obscure cases where you would want to declare iVars instead of properties but I can't think of any.

    3 Xcode will create an iVar with the same name as the property, preceded by an _underscore. If you (rarely) need some other kind of behaviour, you can manually @synthesize property = someOtherName. @vikingosegundo links us to this article on dynamic ivars, which is a use case for @synthesize. @RobNapier comments that you do need to @synthesize iVar = _iVar (bizarrely) if you are creating your own getters (readonly) and setters (read/write) for a property, as in this case the preprocessor will not generate the iVar for you.

    4 The general rule with your interface: keep it as empty as possible. You don't actually need to declare your methods now at all, if they are for private use. If you can get the code to work without an interface declaration, that's the way to go.

    5 This is an @interface block in your .m file, placed above your @implementation:

    #TestClass.m
    
    @interface TestClass()
    
    //private property declarations here
    
    @end
    
    @implementation TestClass
    ...
    
    0 讨论(0)
提交回复
热议问题