【问题标题】:why does this code not work for referencing a const from a class?为什么这段代码不能用于从类中引用 const?
【发布时间】:2011-09-16 01:58:41
【问题描述】:

为什么这段代码不能用于从类中引用 const?

背景:我希望能够以类变量类型方法从类中引用常量值,因为这是有意义的来源。尝试找到有效地让类提供暴露常量的最佳方法。我尝试了以下方法,但它似乎不起作用,我得到“错误:在'DetailedApppointCell'类型的对象上找不到属性'titleLablePrefix'”

@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'

【问题讨论】:

标签: iphone objective-c ios constants class-variables


【解决方案1】:

如果您的外部链接正确,您可以直接使用NSString *str = titleLablePrefix;

【讨论】:

  • “如果您的外部链接正确”是什么意思。我刚刚尝试了您的建议,有趣的是,它适用于一个这样的变量,但不适用于另一个 - 它不适用于我得到的那个:体系结构 i386 的未定义符号:/ ld:未找到体系结构 i386/collect2 的符号: ld 返回 1 个退出状态”。
【解决方案2】:

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];

附言点语法用于实例属性。您可以在此处了解有关 Objective C 的更多信息:http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html

【讨论】:

    猜你喜欢
    • 2017-05-13
    • 1970-01-01
    • 2012-07-06
    • 2019-11-20
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2019-08-18
    相关资源
    最近更新 更多