2011-06-16 70 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

相关问题