Ios 类中的extern NSString*常量。
嗨,我有这个头文件:Ios 类中的extern NSString*常量。,ios,iphone,objective-c,nsstring,extern,Ios,Iphone,Objective C,Nsstring,Extern,嗨,我有这个头文件: #import <Foundation/Foundation.h> @interface PCConstants : NSObject extern NSString *const kPCUserProfileKey; extern NSString *const kPCUserProfileNameKey; extern NSString *const kPCUserProfileFirstNameKey; extern NSString *const kP
#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
当我在.pch文件中导入头文件时,我可以在任何地方访问常量。但我试着去了解发生了什么
我从未分配初始化这个对象,所以它们不能是实例常量。所以常量必须是“类对象常量”,对吗?但我认为类对象不能包含数据
有人能解释一下吗?那些
extern
变量是应用程序级全局变量。它们的作用域不限于类,也不限于类的实例
Objective-C不支持实例级或类级全局变量
如果需要类级常量,则需要定义类方法来访问它们。如果需要实例级常量,则需要定义实例方法或只读属性来访问它们。AFAIK Objective C不支持实例级常量。因此,您的常量可能被视为具有文件作用域。这与这就是你看到的行为。好吧,它们与类无关……所以它不是一个对象,它们是指向可变对象的常量指针。事实上,我相信从技术上讲,使用运行时和元类向类中添加ivar是可能的。我不建议这样做…@pic-o-matic:它们是指向不可变对象的常量指针对象(精确地说是常量字符串)。
#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