理解Objective-C的变量以及面相对象的继承特性

2020-01-14 18:59:31刘景俊
易采站长站为您分析理解Objective-C的变量以及面相对象的继承特性,文中的所说的点语法即是'对象名.成员变量名'这种对变量的访问,需要的朋友可以参考下  

OC点语法和变量作用域

一、点语法

(一)认识点语法

声明一个Person类:

复制代码
#import <Foundation/Foundation.h>

 

@interface Person : NSObject
{
    int _age;//默认为@protected
}

- (void)setAge:(int)age;
- (int)age;

@end


Person类的实现:
复制代码
#import "Person.h"

 

@implementation Person

- (void)setAge:(int)age
{
    _age = age;// 不能写成self.age = newAge,相当与 [self setAge:newAge];
}

- (int)age  //get方法
{
    return _age;
}

@end


点语法的使用:
复制代码
#import <Foundation/Foundation.h>
#import "Person.h"

 

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        Person *person = [[Person alloc] init];
        
        //[person setAge:10];
        person.age = 10;//点语法,等效与[person setAge:10];
//这里并不是给person的属性赋值,而是调用person的setAge方法
        
        //int age = [person age];
        int age = person.age;//等效与int age = [person age]
       NSLog(@"age is %i", age);
        [person release];
        
    }