Objective c 如何从类目标C外部获取和设置私有实例变量/属性?
我有一个带有属性/变量Objective c 如何从类目标C外部获取和设置私有实例变量/属性?,objective-c,ios7,Objective C,Ios7,我有一个带有属性/变量NSString*url的MyConfig类。私下说,我不希望任何人能够在MyConfig类之外设置url。例如,我不希望允许以下情况: MyConfig * myConfig = [[MyConfig alloc] init]; myConfig.url = @"some url";// I want to forbid this 我的目标: forbit通过点表示法设置变量/属性 使用自动生成的/标准getter(myConfig.url)和setter([myCo
NSString*url
的MyConfig类。私下说,我不希望任何人能够在MyConfig类之外设置url。例如,我不希望允许以下情况:
MyConfig * myConfig = [[MyConfig alloc] init];
myConfig.url = @"some url";// I want to forbid this
我的目标:
- forbit通过点表示法设置变量/属性
- 使用自动生成的/标准getter(
)和setter(myConfig.url
)-我不想编写 我自己是个能手和二传手[myConfig setUrl]
@interface MyConfig : NSObject
@property (readonly) NSString * url;
@end
问题:标准getter不工作
MyConfig * myConfig = [[MyConfig alloc] init];
[myConfig setUrl];// Instance method "-setUrl:" not found (return default type is "id")
这不应该是这样,对吗
有更好的方法来实现我的目标吗?您可以尝试为getter创建一个公共属性,如您已经创建的,然后在实现文件中创建私有版本,如下面所示 MyConfig.h
// Public interface that the world can see
@interface MyConfig : NSObject
@property (readonly) NSString *url; // Readonly so the getter will be generated but not the setter
@end
MyConfig.m
#import "MyConfig.h"
// Private interface that only your implementation can see
@interface MyConfig() // Class extension
@property (nonatomic, strong) NSString *url; // Private getter and setter
@end
@implentation MyConfig
// The rest of your code...
@end
我实现这一点的方法是使用类扩展,声明类扩展的语法与创建空名称类别的语法相同。此外,相当重要的一部分是,我们不必定义另一个实现块,这个扩展的实现和其中的代码必须在主实现块中实现
使用类扩展方法(不适用于类别),我们可以拥有一个属性,该属性具有面向公众的
readonly
access和面向私人的readwrite
access。为此,我们在头文件中将属性声明为readonly
,并在类扩展名中将其重新声明为readwrite
。最简单的方法是在实现(.m)文件中声明此属性:
您可以覆盖setter并在其中抛出异常。没问题,我希望它能有所帮助。
@interface MyConfig () //This declares a category/extension to your header file
@property (nonatomic, strong) NSString * url; //This property is private
@end
@implementation MyConfig
//Your code
@end