在Objective-C中只写属性 [英] Write only property in Objective-C

查看:146
本文介绍了在Objective-C中只写属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持使用objective-c属性。我需要的是为变量分配一个只写属性,与readonly完全相反,即变量可以有 setMethod ,但它不应该有 getMethod 。我不知道怎么做。一些代码片段的答案很受欢迎。

I am stuck with objective-c properties. What I need is to assign a write-only property for a variable, exactly the opposite of readonly, i.e the variable can have setMethod, but it should not have getMethod. I don't know how to do it. answers with some code snippets are appreciated.

推荐答案

你可以这样做:

@interface MyClass {
@private
int _var;
}

- (void)setVar:(int)newVar;
@end

@implementation MyClass
- (void)setVar:(int)newVar {
_var = newVar;
}
@end

现在你可以访问变量 var 就像一个只写的属性:

Now you can access the variable var like a property that is write-only:

@implementation SomeOtherClass
...
MyClass c = [[MyClass alloc] init];
c.var = 3;
...
@end

如果你试试看假货属性编译器会警告你。

And if you try to read the fake property the compiler will warning you.

这篇关于在Objective-C中只写属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆