How should private and public members be implemented in objective-c?

前端 未结 3 1621
孤城傲影
孤城傲影 2020-12-13 14:32

I had some discussion related to the use of properties and instance variables at work, therefore I would like to find a wiki answer for that. Now, I know there\'s no real pr

3条回答
  •  难免孤独
    2020-12-13 14:57

    By using class extensions you can have private properties.

    A class extension syntax is simple:

    Inside the .m-file, that has the class, create a unnamed category:

    .h

    @interface OverlayViewController : UIViewController 
    - (IBAction)moreButtonClicked:(id)sender;
    - (IBAction)cancelButtonClicked:(id)sender;
    @end
    

    .m

    #import "OverlayViewController.h"
    
    @interface OverlayViewController ()
    @property(nonatomic) NSInteger amount;
    @property(retain,nonatomic)NSArray *colors;
    @end
    
    @implementation OverlayViewController
    @synthesize amount = amount_;
    @synthesize colors = colors_;
    
    //…
    
    @end
    

    Now you got all the aspects of properties for private members, without exposing them to public. There should be no overhead to synthesized properties to written getter/setters, as the compiler will create more or less the same at compile time.

    Note that this code uses synthesized ivars. No ivar declaration in the header is needed.

    There is a nice cocoawithlove article, about this approach.

    You also ask why to use properties for private ivars. There are several good reasons:

    • properties take care for ownership and memory management.
    • at any point in future you can decide, to write a custom getter/setter. i.e. to reload a tableview, once a NSArray ivar was newly set. If you used properties consequently, no other changes are needed.
    • Key Value Coding support properties.
    • public readonly properties can be re-declared to private readwrite properties.

    Since LLVM 3 it is also possible, to declare ivars in class extensions

    @interface OverlayViewController (){
        NSInteger amount;
        NSArray *colors;
    }
    @end
    

    or even at the implementation block

    @implementation OverlayViewController{
        NSInteger amount;
        NSArray *colors;
    }
    //…
    @end
    

    see "WWDC2011: Session 322 - Objective-C Advancements in Depth" (~03:00)

提交回复
热议问题