2014-01-22 23 views
4

有沒有辦法讓OSX類別和iOS類別擁有一個頭文件和實現文件?我不想讓方法完全相同,並添加另外兩個文件。我可以爲iOS和OSX使用一個類別擴展名.h和.m文件嗎?

我已經試過這一點,這不工作:

#if TARGET_OS_IPHONE 
#define kClass [UIColor class] 
#import <UIKit/UIKit.h> 
#elif TARGET_OS_MAC 
#define kClass [NSColor class] 
#import <AppKit/AppKit.h> 
#endif 

@interface kClass (MyCategory) 

有沒有辦法做到這一點?

回答

6

絕對!請記住#define是編譯前的簡單文本替換:您希望​​爲UIColor,而不是[UIColor class],就像您永遠不會寫@interface [UIColor class] (MyCategory)一樣。

結論:

#if TARGET_OS_IPHONE 
#define kClass UIColor 
#import <UIKit/UIKit.h> 
#elif TARGET_OS_MAC 
#define kClass NSColor 
#import <AppKit/AppKit.h> 
#endif 

@interface kClass (MyCategory) 
+2

你可以看到預處理器做你的文件。在Xcode 5中,您可以使用產品 - >執行操作 - >預處理文件菜單。這會顯示文件在預處理之後但編譯之前的內容。您將能夠看到「簡單文本替換」已經做出。 – mttrb

+1

真棒,這工作!我只需要將這一行添加到其他所有行上:'#include「TargetConditionals.h」' – bennyguitar

相關問題