【问题标题】:extern NSString *const in a class.extern NSString *const 在一个类中。
【发布时间】:2014-03-20 17:02:58
【问题描述】:

您好,我有这个头文件:

#import <Foundation/Foundation.h>

@interface PCConstants : NSObject
extern NSString *const kPCUserProfileKey;
extern NSString *const kPCUserProfileNameKey;
extern NSString *const kPCUserProfileFirstNameKey;
extern NSString *const kPCUserProfileLocationKey;
extern NSString *const kPCUserProfileGenderKey;
extern NSString *const kPCUserProfileBirthDayKey;
extern NSString *const kPCUserProfileInterestedInKey;
@end

实现:

#import "PCConstants.h"

@implementation PCConstants

NSString *const kPCUserProfileKey                  = @"profile";
NSString *const kPCUserProfileNameKey              = @"name";
NSString *const kPCUserProfileFirstNameKey         = @"firstname";
NSString *const kPCUserProfileLocationKey          = @"location";
NSString *const kPCUserProfileGenderKey            = @"gender";
NSString *const kPCUserProfileBirthDayKey          = @"birthday";
NSString *const kPCUserProfileInterestedInKey      = @"interestedIn";

@end

当我在 .pch 文件中导入头文件时,我可以在任何地方访问常量。但我试图了解发生了什么。

我从不分配初始化这个对象,所以它们不能是实例常量。所以常量必须是“类对象常量对吧?但我认为类对象不能包含数据。

谁能解释一下?

【问题讨论】:

  • AFAIK Objective C 不支持实例级常量。因此,您的常量可能被视为具有文件范围。这与您看到的行为一致。

标签: ios iphone objective-c nsstring extern


【解决方案1】:

那些extern 变量是应用级别的全局变量。它们不局限于类,也不局限于类的实例。

Objective-C 不支持实例或类级别的全局变量。

如果你想要类级别的常量,你需要定义类方法来访问它们。如果需要实例级常量,则需要定义实例方法或只读属性来访问它们。

【讨论】:

  • 好的,所以它们与类无关......所以它不是对象,它们是指向可变对象的常量指针。
  • 实际上,我相信使用运行时和元类将 ivar 添加到类中在技术上是可行的。并不是说我会推荐它...
  • @pic-o-matic:它们是指向 immutable 对象的常量指针(准确地说是常量 NSString)。
猜你喜欢
  • 1970-01-01
  • 2011-11-09
  • 2012-08-10
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多