Difference between @interface declaration and @property declaration

前端 未结 6 1998
忘了有多久
忘了有多久 2020-12-23 10:05

I\'m new to C, new to objective C. For an iPhone subclass, Im declaring variables I want to be visible to all methods in a class into the @interface class definition eg

6条回答
  •  死守一世寂寞
    2020-12-23 10:45

    Here, you're declaring an instance variable named aVar:

    @interface myclass : UIImageView {
        int aVar;
    }
    

    You can now use this variable within your class:

    aVar = 42;
    NSLog(@"The Answer is %i.", aVar);
    

    However, instance variables are private in Objective-C. What if you need other classes to be able to access and/or change aVar? Since methods are public in Objective-C, the answer is to write an accessor (getter) method that returns aVar and a mutator (setter) method that sets aVar:

    // In header (.h) file
    
    - (int)aVar;
    - (void)setAVar:(int)newAVar;
    
    // In implementation (.m) file
    
    - (int)aVar {
        return aVar;
    }
    
    - (void)setAVar:(int)newAVar {
        if (aVar != newAVar) {
            aVar = newAVar;
        }
    }
    

    Now other classes can get and set aVar via:

    [myclass aVar];
    [myclass setAVar:24];
    

    Writing these accessor and mutator methods can get quite tedious, so in Objective-C 2.0, Apple simplified it for us. We can now write:

    // In header (.h) file
    
    @property (nonatomic, assign) int aVar;
    
    // In implementation (.m) file
    
    @synthesize aVar;
    

    ...and the accessor/mutator methods will be automatically generated for us.

    To sum up:

    • int aVar; declares an instance variable aVar

    • @property (nonatomic, assign) int aVar; declares the accessor and mutator methods for aVar

    • @synthesize aVar; implements the accessor and mutator methods for aVar

提交回复
热议问题