ios - 类中的 extern NSString *const。

标签 ios iphone objective-c nsstring extern

您好,我有这个头文件:

#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 文件中导入头文件时,我可以在任何地方访问常量。但我试图了解发生了什么。

我从来没有分配初始化这个对象,所以它们不可能是实例常量。所以常量必须是“类对象常量,对吗?但我认为类对象不能包含数据。

谁能解释一下?

最佳答案

那些 extern 变量是应用级全局变量。它们不在类的范围内,也不在类的实例范围内。

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

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

关于ios - 类中的 extern NSString *const。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22540166/

相关文章:

ios - 如何添加背景音乐

ios - 在 iOS7 中 "main" View 下的元素存储(弱或强)

iphone - 如何在iphone中以编程方式获取 "General -> Date & Time -> Set Automatically"的值?

ios - UIImagePickerController导入图像

ios - HKQuantityTypeIdentifier用字符串初始化

ios - 类 "ViewController"的重复接口(interface)定义

objective-c - 如果 iAds 失败,如何集成 iAds 和 AdMob

ios - MagicalRecord-速记适用于某些实体,但不适用于其他实体

ios - 有什么办法可以覆盖 guard 语句吗?

objective-c - 如何制作自定义 tableView 单元配件