【问题标题】:iOS: @encode and accessing subclass's property directly using ->iOS:@encode 并直接使用 -> 访问子类的属性
【发布时间】: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->frameview->_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


【解决方案1】:
[array1 addObject:[NSValue valueWithCGRect:view.frame]];

CGRect rect = [[array1 lastObject] CGRectValue];

文档:NSValue UIKit Additions Reference

【讨论】:

  • 但是我的方法(尽管像其他人声称的那样邪恶,这在某种程度上点燃了我的好奇心)仍然可行吗?您能否详细说明我的方法的好(如果有)和坏处以及它有什么问题?提前致谢。
  • 您的方法是不可能的,因为UIView 没有存储其框架的实例变量。详情请见this answer
  • 你能来的最接近的是[NSValue valueWithBytes:&(CGRect){view.frame.origin, view.frame.size} objCType:@encode(CGRect)],这很混乱,两次调用view.frame
  • 但是在C中获取右值的地址(即&(CGRect))是无效的吗?
  • @Unheilig:(CGRect){view.frame.origin, view.frame.size} 是一个“复合文字”,它是一个左值,比较 gcc.gnu.org/onlinedocs/gcc-3.2.2/gcc/Compound-Literals.html。 (我希望我的术语是正确的。)
猜你喜欢
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2013-06-12
  • 1970-01-01
  • 2019-03-11
相关资源
最近更新 更多