getter 方法與屬性的識別字相同, setter 方法則是在屬性識別字加上 set 。
例如我們有以下的 Demo.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #import <Foundation/Foundation.h> @interface Demo : NSObject { int a; int b; } @property int a, b; - ( int ) do_something; @end /* 《程式語言教學誌》的範例程式 檔名:Demo.h 功能:Objective-c 程式範例 作者:張凱慶 時間:西元 2013 年 4 月 */ |
因為這裡是使用 Xocde 3.2 ,因此要順利編譯成功,仍要已大括弧宣告屬性。
實作檔 Demo.m 如下,注意開始的地方要先 #import "Demo.h"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #import "Demo.h" @implementation Demo @synthesize a, b; - ( int ) do_something { return a + b; } @end /* 《程式語言教學誌》的範例程式 檔名:Demo.m 功能:Objective-c 程式範例 作者:張凱慶 時間:西元 2013 年 4 月 */ |
執行檔如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #import "Demo.h" int main ( int argc, const char * argv[]) { NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc ] init ]; Demo *demo = [[ Demo alloc ] init ]; [demo setA : 11 ]; [demo setB : 22 ]; NSLog( @"a = %d, b = %d" , [demo a ], [demo b ]); NSLog( @"a + b = %i" , [demo do_something ]); [pool drain ]; return 0 ; } /* 《程式語言教學誌》的範例程式 檔名:classdemo03.m 功能:Objective-c 程式範例 作者:張凱慶 時間:西元 2013 年 4 月 */ |
編譯執行,結果如下

中英文術語對照 | |
---|---|
介面 | interface |
屬性 | property |
實作 | implement |
方法 | method |
您可以繼續參考
類別
相關目錄
Objective-C 快速導覽
Objective-C 教材
首頁
參考資料
Programming with Objective-C: About Objective-C
Programming with Objective-C: Working with Objects
沒有留言:
張貼留言