在 Xcode 中用新增檔案的方式,即可同時新增 .m 與 .h 檔案。
例如我們有以下的 Demo.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #import <Foundation/Foundation.h> @interface Demo : NSObject { int a; int b; } - ( int ) a; - ( int ) b; - ( id ) setA : ( int ) pa; - ( id ) setB : ( int ) pb; - ( int ) do_something; @end /* 《程式語言教學誌》的範例程式 檔名:Demo.h 功能:Objective-c 程式範例 作者:張凱慶 時間:西元 2013 年 4 月 */ |
實作檔 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 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #import "Demo.h" @implementation Demo - ( int ) a { return a; } - ( int ) b { return b; } - ( id ) setA : ( int ) pa { a = pa; return self ; } - ( id ) setB : ( int ) pb { b = pb; return self ; } - ( 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 ; } /* 《程式語言教學誌》的範例程式 檔名:classdemo02.m 功能:Objective-c 程式範例 作者:張凱慶 時間:西元 2013 年 4 月 */ |
編譯執行,結果如下

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