When do I need to have both iVar and a property?

前端 未结 2 837
北海茫月
北海茫月 2021-01-28 04:21

I see some examples sometimes would declare a property as well as variable other times they do not .e.g. some time I see code like this

@interface Test : NSObjec         


        
相关标签:
2条回答
  • 2021-01-28 04:48

    Using ivars instead properties is only useful if you want @protected access (access from subclasses only), or support the old runtime (which required both).

    0 讨论(0)
  • 2021-01-28 04:52

    It depends whether the property is synthesized against an iVar or derived in some other way (or against another iVar).

    IF we have an instance of the class - i.e:

    Test *myTest = [[Test alloc] init];
    

    Then basically the property declaration

    @property (nonatomic,retain)UIProgressView* progressView;
    

    is telling anyone interested in using the interface that they can access the following two functions on an instance of this class:

    [myTest progressBar];
    [myTest setProgressBar:aProgressBar];
    

    And objective C also lets you use shorthand notation:

    myTest.progressBar =
    xxx = myTest.progressBar
    

    which does exactly the same thing.

    It is not necessary for these two methods to be implemented via an iVar of the same name as the property, or even via an iVar at all (they could do even do a database fetch or derive the value).

    If you @synthesize the property (which means you want the precompiler to generate the above methods for you) and don't explicitly specify an iVar on the @synthesize directive, then the methods described above will automatically be generated (due to the synthesize method) to set or get the value to/from an iVar of the same name as the property (and the implementation will include retain/release logic depending on the property directive.

    If you don't @synthesize the property then you provide your own implementation and it can be anything you want. It is also possible to @synthesize the property but include a directive to use a different iVar in the method definition:

    @synthesize progressBar=someOtheriVar;
    

    in which case you will not see an iVar of the same name as the property in the header file either.

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