extern NSString * const在一个类中。

嗨,我有这个头文件:

#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文件中导入头文件时,我可以随处访问常量。 但是我试图理解发生了什么事情。

我从来没有分配init这个对象,所以他们不能是实例常量。 所以常量必须是“类对象常量是正确的?但我认为类对象不能包含数据。

有人可以解释吗?

那些externvariables是应用程序级别的全局variables。 它们不属于这个类的范围,它们没有作用于该类的一个实例。

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

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