您好,我有这个头文件:
#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 文件中导入头文件时,我可以在任何地方访问常量。但我试图了解发生了什么。
我从来没有分配初始化这个对象,所以它们不可能是实例常量。所以常量必须是“类对象常量,对吗?但我认为类对象不能包含数据。
谁能解释一下?
最佳答案
那些 extern
变量是应用级全局变量。它们不在类的范围内,也不在类的实例范围内。
Objective-C 不支持实例或类级别的全局变量。
如果你想要类级别的常量,你需要定义类方法来访问它们。如果你想要实例级常量,你需要定义实例方法或只读属性来访问它们。
关于ios - 类中的 extern NSString *const。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22540166/