extern NSString *const in a class.

2019-06-20 04:08发布

问题:

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.