ios – 类中的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,因此它们不能是实例常量.所以常量必须是“类对象常量对吗?但我认为类对象不能包含数据.

谁能解释一下?

解决方法

那些外部变量是app级全局变量.它们没有作用于类,它们不限于类的实例.

Objective-C不支持实例或类级别全局变量.

如果需要类级别常量,则需要定义类方法以访问它们.如果需要实例级常量,则需要定义实例方法或只读属性才能访问它们.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...