ios – 类中的extern NSString * const.

前端之家收集整理的这篇文章主要介绍了ios – 类中的extern NSString * const.前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我有这个头文件
  1. #import <Foundation/Foundation.h>
  2.  
  3. @interface PCConstants : NSObject
  4. extern NSString *const kPCUserProfileKey;
  5. extern NSString *const kPCUserProfileNameKey;
  6. extern NSString *const kPCUserProfileFirstNameKey;
  7. extern NSString *const kPCUserProfileLocationKey;
  8. extern NSString *const kPCUserProfileGenderKey;
  9. extern NSString *const kPCUserProfileBirthDayKey;
  10. extern NSString *const kPCUserProfileInterestedInKey;
  11. @end

执行:

  1. #import "PCConstants.h"
  2.  
  3. @implementation PCConstants
  4.  
  5. NSString *const kPCUserProfileKey = @"profile";
  6. NSString *const kPCUserProfileNameKey = @"name";
  7. NSString *const kPCUserProfileFirstNameKey = @"firstname";
  8. NSString *const kPCUserProfileLocationKey = @"location";
  9. NSString *const kPCUserProfileGenderKey = @"gender";
  10. NSString *const kPCUserProfileBirthDayKey = @"birthday";
  11. NSString *const kPCUserProfileInterestedInKey = @"interestedIn";
  12.  
  13. @end

当我在.pch文件中导入头文件时,我可以在任何地方访问常量.但我试着了解发生了什么.

我从不为此对象分配init,因此它们不能是实例常量.所以常量必须是“类对象常量对吗?但我认为类对象不能包含数据.

谁能解释一下?

解决方法

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

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

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

猜你在找的iOS相关文章