【发布时间】:2014-02-20 07:12:37
【问题描述】:
我有一个NSMutableArray,我想在其中存储一些CGRects:
所以,我尝试使用以下(例如):
UIView *view = [[UIView alloc] initWithFrame:(CGRect){{0, 0}, 50, 50}];
[array1 addObject:[NSValue value:&view->frame withObjCType:@encode(CGRect)]];
但这会导致警告:&view->frame
这是一个属性,但我想直接访问它,这样我就可以使用上面的语法并将它用于上面的value: 参数。
我知道我可以访问&self->_view(如果我想将视图添加到数组中,这里不是这种情况),所以我尝试了&view->frame(甚至&view->_frame),但它会导致警告并且不起作用。
它会,除非我先这样:
CGRect tempRect = view.frame;
[array1 addObject:[NSValue value:&tempRect withObjCType:@encode(CGRect)]];
所以我的问题是,我在这里对&view->frame(甚至:&view->_frame)做错了什么?
而且有没有办法做到这一点而不必先这样做:
CGRect tempRect = view.frame;
[array1 addObject:[NSValue value:&view->frame withObjCType:@encode(CGRect)]];
换句话说,我可以在这里简单地使用演员表,而不必先创建CGRect(tempRect)吗?
附录:
如果我没记错的话,我认为在 C 中强制转换 & 是无效的。不确定,如果我的记忆正确,请告诉我。
【问题讨论】:
-
这看起来很邪恶。为什么不对 NSValue 使用 CGRect 类别呢? developer.apple.com/library/ios/documentation/uikit/reference/…
-
您不能使用
view->frame或view->_frame,因为UIView在其公共接口中没有实例变量frame 或_frame! - 正如 Stefan 建议的那样,使用valueWithCGRect:是最好的解决方案。 -
@StefanFisk 你能解释一下它的邪恶吗?
-
@MartinR 对,但我认为
CGRect只是一个结构,因为我们可以对struct做同样的事情,所以我想我会尝试这样做。我听说过使用[NSValue valueWithCGRect:view.frame],但我想知道我的方法是否仍然可行,并希望从中学到一些东西(好的或坏的)。 -
@Unheilig:我假设 Stefan 在谈到“邪恶”时指的是您直接访问实例变量。 -
[NSValue value:&tempRect withObjCType:@encode(CGRect)]看起来不错,只是value:objCType:已弃用,您应该使用valueWithBytes:objCType:。但是如果有一个专用的方法valueWithCGRect:那么应该使用它。
标签: ios objective-c c encode cgrect