extern NSString *const in a class.

人走茶凉 提交于 2019-12-23 09:41:52

问题


Hi I've got this header file:

#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

implementation:

#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

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.

Can someone explain?


回答1:


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 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.



来源:https://stackoverflow.com/questions/22540166/extern-nsstring-const-in-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!