混合C结构和Objective-C属性 [英] Mixing C Structs and Objective-C Properties

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

问题描述

我已经定义了一个具有CGPoint ivar和相关属性的对象,如下所示...

I have defined an object with a CGPoint ivar and associated property as follows...

@interface Sprite : NSObject {
 CGRect boundingBox;
}
@property(assign) CGRect boundingBox;

当我使用Sprite类的实例并按如下所示尝试更新boundingBox结构时...

When I use an instance of the Sprite class and try and update the boundingBox struct as follows...

self.boundingBox.origin.x = minX;

我收到一个编译时错误提示...

I receive a compile time error stating...

需要左值作为左操作数 作业

Lvalue required as left operand of assignment

我正确地说是self.boundingBox将返回C结构,它实际上不是Sprite对象持有的结构,而是它的副本吗?因此,当为x分配新值失败时,是因为该结构只是一个临时副本?

Am I correct in saying that self.boundingBox will return a C struct, which isn't actually the struct held by the Sprite object but rather a copy of it? Therefore when the assignment of a new value for x fails because the struct is only a temporary copy?

如果是这种情况,以下代码是否可以正常工作(这是实现我想要的正确方法)?

If this is the case will the following code work correctly (and is it the correct way to achieve what I want)?

CGRect newBoundingBox = self.boundingBox;
newBoundingBox.origin.x = self.boundingBox.origin.x;
self.boundingBox = newBoundingBox;

推荐答案

已解决的问题:我最初关于无法编辑任何CGRect的评论是错误的.第一行代码的实际问题来自您正在使用self.boundingBox访问CGRect的事实.您的第二个代码以及我在原始答案中使用的代码块将非常有用:

EDITED ANSWER: My original comment about not being able to edit any CGRect was wrong; the actual problem with that first line of code comes from the fact that you're using self.boundingBox to access the CGRect. Your second code will work great, along with the block I had in my original answer:

要正确更改boundingBox中的值,您需要使用apple的CGRectMake函数,如下所示:

To properly change values inside boundingBox, you'll need to use apple's CGRectMake function, like so:

CGRect r = self.boundingBox;
self.boundingBox = CGRectMake(minX, r.y, r.width, r.height);

有关为什么self.表示法是结构问题的一个很好的解释,请查看这个问题.希望这会有所帮助!

For a nice explanation of why the self. notation is a problem with structs, check out the answers to this question. Hope this helps!

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

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