Objective-C中get/set方法初探(1)

乞力馬紮羅的雪CYF發表於2015-09-20

     在其他語言或者專案開發中,對一個變數的存取常常使用的是set get方法,在OC中也是如此,並且也是非常方便。

(1)新建一個People類,在People.h中宣告一個屬性。宣告之後,系統會預設建立這個屬性的set/get方法;

#import <Foundation/Foundation.h>

@interface People : NSObject

@property int age;

@end

(2)在main.m中實現如下:

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "People.h"


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

 
  People *people = [[People alloc] init];
  
  //使用預設的age的set方法;
  [people setAge:20];
  
  //使用預設的age的get方法,注意不是getAge哦,而是直接age;
  NSLog(@"%d",[people age]);

}

總結,只要是在標頭檔案中宣告的屬性,系統都會預設建立set、get方法,當然這能實現最基本的功能。但一般情況下,我們需要重寫set,get方法,以完成更多的功能。


github主頁:https://github.com/chenyufeng1991  。歡迎大家訪問!

相關文章