类中的extern NSString * const. [英] extern NSString *const in a class.
问题描述
我有这个头文件:
#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文件中导入头文件时,我可以在任何地方访问常量.但是我试图了解发生了什么.
When I import the header file in my .pch file, I can access the constants everywhere. But I try to understand what's going on.
我从不分配初始化对象,所以它们不能是实例常量.因此,这些常量必须是类对象常量对吗?但是我认为类对象不能包含数据.
I never alloc init this object, so they can't be instance constants. So the constants must be "class object constants right? But I thought class objects could not contain data.
有人可以解释吗?
推荐答案
这些extern
变量是应用程序级的全局变量.它们没有作用于该类,也没有作用于该类的实例.
Those extern
variables are app-level globals. They are not scoped to the class and they are not scoped to an instance of the class.
Objective-C不支持实例或类级别的全局变量.
Objective-C does not support instance or class level globals.
如果要使用类级别的常量,则需要定义类方法来访问它们.如果需要实例级常量,则需要定义实例方法或只读属性以访问它们.
If you want class level constants, you need to define class methods to access them. If you want instance level constants, you need to define instance methods or read-only properties to access them.
这篇关于类中的extern NSString * const.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!