2011-06-16 56 views
0

爲什麼此代碼不能用於從類引用常量?爲什麼此代碼不能用於從類引用常量?

背景:我希望能夠在類變量類型的方法中引用類中的常量值,因爲這是源代碼有意義的地方。嘗試找到有效讓班級提供暴露常數的最佳方式。我試過以下,但它似乎沒有工作,我得到:

@interface DetailedAppointCell : UITableViewCell { 
} 
    extern NSString * const titleLablePrefix; 
@end 

#import "DetailedAppointCell.h" 
@implementation DetailedAppointCell 
    NSString * const titleLablePrefix = @"TITLE: "; 
@end 

// usage from another class which imports 
NSString *str = DetailedAppointCell.titleLablePrefix; // ERROR: property 'titleLablePrefix' not found on object of type 'DetailedAppointCell' 
+0

check [this](http://stackoverflow.com/questions/538996/constants-in-objective-c) – 2011-06-16 05:51:54

回答

2

如果外部聯繫是可以直接用作NSString *str = titleLablePrefix;「ERROR財產‘titleLablePrefix’上鍵入‘DetailedAppointCell’對象找不到」正確。

+0

你是什麼意思「如果你的外部鏈接是正確」。我只是嘗試了你的建議,有趣的是它適用於一個這樣的變量,但不是另一個 - 它沒有爲我工作的那個:未定義的架構i386符號:/ ld:符號(s)找不到架構i386/collect2: ld返回1退出狀態「 – Greg 2011-06-16 05:37:34

+1

我的壞 - 有一個錯字,這似乎工作正常 – Greg 2011-06-16 05:48:34

1

Objective C不支持類變量/常量,但它支持類方法。您可以使用以下解決方案:

@interface DetailedAppointCell : UITableViewCell { 
} 
+ (NSString*)titleLablePrefix; 
@end 

#import "DetailedAppointCell.h" 
@implementation DetailedAppointCell 
+ (NSString*)titleLablePrefix { 
    return @"TITLE: "; 
} 
@end 

// usage from another class which imports 
NSString *str = [DetailedAppointCell titleLablePrefix]; 

p.s.點語法用於實例屬性。你可以在這裏瞭解更多關於Objective C的信息:http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html

相關問題