如何在 Objective-C 中的原子属性 ivar 上创建手动锁定?
我想在 obj-c 类中公开一个原子属性,但在内部我更愿意直接访问它的实例变量,而不是对每个引用使用 self.myproperty 。如何手动创建锁来阻止外部读?
所以我想……
@property (atomic, strong) NSString *someString;
- myInternalMethodOfClassA
{
...
@synchronized(someString) {
someString = @"New string";
}
...
}
阻止……
- myInstanceMethodInClientClassB
{
ClassA *myobj = [ClassA alloc] init];
...
NSString *str = myobj.someString;
...
}
I want to expose an atomic property in my obj-c class, but internally I'd prefer to access it's instance var directly rather using self.myproperty
for every reference. How do you manually create a lock to block the external read?
So I want...
@property (atomic, strong) NSString *someString;
- myInternalMethodOfClassA
{
...
@synchronized(someString) {
someString = @"New string";
}
...
}
...to block...
- myInstanceMethodInClientClassB
{
ClassA *myobj = [ClassA alloc] init];
...
NSString *str = myobj.someString;
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据Apple Objc-lang 列表上的一些聊天,如果您手动创建一个访问器并合成另一个访问器,则具有原子属性被认为是一个错误。替代方案是:
@synchronized(anObject)
,然后您可以在类代码的其他位置使用它。@synthesize
它们并始终通过其访问器访问它们(即内部的self.myAtomicProp
)。这比较慢,但在几乎所有情况下很可能不是问题。According to some chat on the Apple Objc-lang list, it's considered a bug to have an atomic property for which you manually create one accessor and synthesize the other. The alternatives are:
@synchronized(anObject)
, which you can then use elsewhere in your class's code.@synthesize
them and always access them via their accessors (ieself.myAtomicProp
internally). This is slower but most likely not a problem in nearly all cases.