在其他类的类中使用 CGPoint 属性并出现左值错误
我在使用 cocos2D 的 Objective C 中有两个主要类,DebugZoneLayer 和 HeroClass。使用 Cocos2D 可能不是问题的一部分。
HeroClass 包含一个 CGPoint 和一个属性。我在 DebugZoneLayer 中有一个 HeroClass 实例,初始化如下:hero = [[HeroClass alloc] init];
我的 HeroClass.h 被缩短以向您展示如何创建 CGPoint vel。
@interface HeroClass : CCLayer {
@public CGPoint _vel;
}
@property(assign) CGPoint vel;
在 HeroClass.m 中,我合成我的属性,如 @synthesize vel = _vel;
在 DebugZoneLayer.m 中,我可以引用我的 Hero.vel x 或 y 就可以了,但任何为 Hero.vel 赋值的内容都可以x 或 y 返回错误:需要左值作为赋值的左操作数
I have two major classes in objective C using cocos2D, DebugZoneLayer and HeroClass. Using Cocos2D may not be part of the issue.
HeroClass contains a CGPoint and a property. I have an instance of HeroClass in DebugZoneLayer initialized like hero = [[HeroClass alloc] init];
My HeroClass.h shortened to show you how I create a CGPoint vel.
@interface HeroClass : CCLayer {
@public CGPoint _vel;
}
@property(assign) CGPoint vel;
In HeroClass.m I synthesize my property like @synthesize vel = _vel;
In DebugZoneLayer.m, I can reference my hero.vel x or y just fine, but anything that assigns a value to hero.vel x or y returns the error: Lvalue required as left operand of assignment
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没错——你不能那样做。属性只是一个方法调用,Objective-C 中的方法总是按值返回,这意味着返回的 CGPoint 只是一个临时 CGPoint,其值与对象中的值相同。不允许设置此临时值的组成部分。您需要在类上为点的 X 和 Y 值创建特殊的设置器,或者一次设置整个点。
That's right — you can't do that. A property is just a method call, and methods in Objective-C always return by value, meaning the CGPoint that gets returned is just a temporary CGPoint with the same value as the one in your object. Setting the components of this temporary value isn't allowed. You'll need to either create special setters on your class for the point's X and Y values or set the whole point at a time.
以不同的方式重述 Chuck 的完全正确答案。
你的问题是 CGPoint 不是 Objective-c 对象,它们是 C 结构。您的属性 *_vel* 不是对象的实例,例如 NSArray、NSArray 或 DebugZoneLayer。
作为一个简单而懒惰的示例,使用 int 而不是结构体和一些伪代码..
您无法像这样设置 _numberOfLives 的值..
更改 bar 的值不会改变foo 的 _numberOfLives 实例变量的值,因为当您调用 -livesRemaining 时,bar 被设置为当前值的副本_numberOfLives。
简而言之,你需要学习一些 C。
Restating Chuck's entirely correct answer in a different way..
Your problem is that CGPoints are not Objective-c Objects, they are C Structs. Your property *_vel* is not an instance of an Object, like an NSArray, NSArray or DebugZoneLayer.
As a simple and lazy example, using an int instead of a struct and a bit of psuedocode..
you couldn't set the value of _numberOfLives like this..
Changing the value of bar won't change the value of foo's _numberOfLives instance variable because when you called -livesRemaining, bar was set to a copy of the current value of _numberOfLives.
In short, you need to learn you some C.