程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> Objective-C基礎筆記(2)@property和@synthesize

Objective-C基礎筆記(2)@property和@synthesize

編輯:關於C語言

Objective-C基礎筆記(2)@property和@synthesize


先貼出使用@property和@synthesize實現的上一篇中的代碼,再解釋這兩個關鍵字的用法和含義,代碼如下:

Person.h文件

#import 

@interface Person : NSObject {
    int _age;  //可以被子類訪問
    //這裡系統會幫我們生成一個默認的 int _no 私有變量(不能被子類訪問)
}

@property int age;
@property int no;

//自己寫一個構造方法
- (id)initWithAge:(int)age andNo:(int)no;

@end
Person.m文件

#import "Person.h"

@implementation Person

//Xcode 4.5以上都不用寫下面兩句(可省略,並且默認是_age和_no)
//@synthesize age = _age; //聲明為protected
//@synthesize no = _no; //默認生成的是私有的

- (id)initWithAge:(int)age andNo:(int)no {
    if(self = [super init]){
        _age = age;
        _no = no;
    }
    return self;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"age is %i and no is %i", _age, _no];
}

@end
main.m文件

#import 
#import "Person.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [[Person alloc] initWithAge:15 andNo:2];
        
        NSLog(@"age is %i and no is %i", person.age, person.no);
        
        [person setNo:3];
        NSLog(@"no is %i", [person no]);
        //%@代表打印一個OC對象
        NSLog(@"%@", person);
    }
    return 0;
}
輸出結果:

2014-11-12 21:53:15.406 firstOCProj[826:47802] age is 15 and no is 2

2014-11-12 21:53:15.407 firstOCProj[826:47802] no is 3

2014-11-12 21:53:15.408 firstOCProj[826:47802] age is 15 and no is 3

可以看到上面的代碼簡潔了不少,@property的作用就等價於對成員變量的聲明,@synthesize的作用就等價於對成員變量setter和getter的標准實現。

需要注意的是:

1、在Xcode4.5以上可以不用寫@synthesize屬性(編譯器默認添加)。

2、這種寫法可以和前面的寫法(舊的寫法)交叉使用。

3、如果要對setter或者getter方法有特殊處理,可以使用舊的寫法(編譯器就不會默認幫我們實現)。

4、如果沒有顯式的聲明變量,則默認生成一個私有成員變量(不能被子類使用,如上面的_no)。

下面我們將上面代碼該的更簡單一些:

Person.h

#import 

@interface Person : NSObject

@property int age;
@property int no;

@end
Person.m

#import "Person.h"

@implementation Person

@end
main.m

#import 
#import "Person.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [Person new];
        [person setAge:20];
        [person setNo:3];
        NSLog(@"age is %i and no is %i", person.age, person.no);
    }
    return 0;
}
輸出結果:

2014-11-12 22:14:44.002 firstOCProj[849:52867] age is 20 and no is 3

注意:我的編譯器Xcode是4.5以上的,所以能省略Person.m中的@synthesize屬性。

這裡不得不對OC和Xcode編譯器感歎,如此方便和好用的工具我真心是第一次見,默默的贊一下。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved