简体   繁体   English

Objective-C属性,只读公开,但有私有的setter

[英]Objective-C property that is readonly publicly, but has a private setter

I'd like to use the @property syntax to declare a synthesized property that is publicly readonly but has a setter that can be called privately from within the class. 我想使用@property语法声明一个公开只读的合成属性,但是有一个可以在类中私下调用的setter。

Since it's Objective-C, this basically means that the setFoo: method would be synthesized, but calling it outside of the class itself would result in a warning (unrecognized selector). 由于它是Objective-C,这基本上意味着将合成setFoo:方法,但是在类本身之外调用它将导致警告(无法识别的选择器)。 To trigger the warning I have to declare the property readonly ; 要触发警告,我必须readonly声明属性; is there any way to force a synthesized setter that is only available within the class? 有没有办法强制合成的setter只在类中可用?

I think what you're looking for are called class extensions. 我认为你正在寻找的是类扩展。 You would declare the property read-only in the header: 您可以在标头中将该属性声明为只读:

@interface MyClass : NSObject {
}

@property (readonly, assign) NSInteger myInteger;

@end

Then redeclare in your class extension in the implementation file: 然后在实现文件中的类扩展中重新声明:

@interface MyClass ()

@property (readwrite, assign) NSInteger myInteger;

@end


@implementation MyClass

@end

For more check out Apple's documentation 有关Apple的文档,请查看更多信息

I might be late, but without extension i did using the following technique 我可能会迟到,但没有扩展我使用了以下技术

@interface MyClass : NSObject {
 NSString * name;
}

@property (readonly, strong) NSString * name;

@end

on the other hand in implementation file 另一方面在实现文件中

@implementation MyClass
 @synthesize name;

 - (id)initWithItems:(NSDictionary *)items {
self = [super init];
if(self)
{ 
  name = @"abc";
}

return self;
}

@end

doing so it will set your value and will be accessible as readonly. 这样做,它将设置您的价值,并将以只读方式访问。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM