Using instance variables with Modern Runtime

前端 未结 5 1794
悲哀的现实
悲哀的现实 2020-12-14 23:43

I have several years of experience in Obj-c and Cocoa, but am just now getting back into it and the advances of Obj-C 2.0 etc.

I\'m trying to get my head around the

5条回答
  •  春和景丽
    2020-12-15 00:11

    There is another SO question with similar information, but it isn't quite a duplicate.

    The bottom line, from the Objective-C 2.0 documentation, and quoted from Mark Bessey's answer is as follows:

    There are differences in the behavior that depend on the runtime (see also “Runtime Differences”):

    For the legacy runtimes, instance variables must already be declared in the @interface block. If an instance variable of the same name and compatible type as the property exists, it is used—otherwise, you get a compiler error.

    For the modern runtimes, instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.

    My understanding is as follows:

    You should not use property accessors in init* and dealloc methods, for the same reasons that you should not use them in the legacy runtime: It leaves you open to potential errors if you later override the property methods, and end up doing something that shouldn't be done in init* or dealloc.

    You should be able to both synthesize the ivar and override the property methods as follows:

    @interface SomeClass
    {
    }
    @property (assign) int someProperty;
    @end
    
    @implementation SomeClass
    @synthesize someProperty; // this will synthesize the ivar
    - (int)someProperty { NSLog(@"getter"); return someProperty; }
    - (void)setSomeProperty:(int)newValue
    {
        NSLog(@"setter");
        someProperty = newValue;
    }
    @end
    

    Which leads me to think that you would be able to access the synthesized ivar in your init* and dealloc methods as well. The only gotcha I could think of is that the @synthesize line may have to come before the definitions of your init* and dealloc methods in the source file.

    In the end, since having the ivars declared in the interface still works, that is still your safest bet.

提交回复
热议问题