1

这是我所拥有的:

@interface engine : NSObject
{

    int test;

}

@property (nonatomic, readonly) int test;

当我尝试在我自己的类(引擎类)中为 iVar 测试分配值(10)时,调试器显示 test = 10 和 _test = 0。

当我尝试从测试中读取时,我得到 0,我猜我得到了 of_test 的值。

我如何让它按照它应该的方式工作?我希望外部班级对“测试”具有只读访问权限,但在我的班级内,我可以向/从“测试”分配和读取值吗?

或者这个实现有什么问题?

更新:我没有合成,因为我使用的是 xcode 4.4,它会自动为你做。我假设合成将使用与属性相同的 iVar 名称。如果您进行正常合成,这无论如何都是默认行为。

谢谢。

4

3 回答 3

1

Automatic synthesize creates an instance variable with a underscore prefix, so a property called test generates a backing instance variable of _test. So you have two instance variables; test, which isn't connected to the property, and _test. If you write to the instance variable test, it will not be reflected in _test or the property's value.

But more to the point, declaring the backing instance variable yourself is pointless. It's just an extra code and unnecessary redundancy. The @property line already contains type, name, whether it's read/write or read-only and a storage qualifier. Just skip declaring the backing instance variable yourself and use the one the compiler generates for you.

In Engine.h:

@interface Engine : NSObject
@property (readonly, assign) NSInteger test;
- (void)doSomething;
@end

In Engine.m:

@implementation Engine

- (void)doSomething {
    _test++; // _test is created automatically by the compiler
}

@end

In other.m:

Engine *engine = [[Engine alloc] init];
NSLog(@"%d", engine.test); // 0
[engine doSomething];
NSLog(@"%d", engine.test); // 1

This all just works. Don't add to it.

于 2012-09-06T05:22:03.780 回答
1

你假设错了。默认实现是生成带有下划线的属性名称。如果你想要一个不同的名字,你需要自己合成它。

于 2012-09-06T05:15:39.733 回答
1

没有看到你的代码很难说,但我猜,你正在尝试做类似的事情,test=10而不是self.test=10. 根据您使用的 ObjC/XCode 版本和可能的@synthesize语句,您正在访问一个(无论定义的)局部变量,而不是属性 resp。是 iVar。

编辑

当你想写一个只读属性时,你应该使用它的 iVar。例如,在_test=10两次读取访问之后,self.test并且_test(但不是纯粹test的!)应该提供相同的值。

于 2012-09-06T04:27:09.523 回答