在 Objective-C 中发送消息时可以强制转换吗?
我有:
[[[[self navigationItem] leftBarButtonItem] customView] setTitle:@" Create "];
这触发了警告“'UIView'可能不会响应'-setTitle:'”。我尝试过:
[[[[self navigationItem] leftBarButtonItem] (UIButton*)customView] setTitle:@" Create "];
当我这样做时会出现错误。 0我还尝试使用 (id) 进行转换,但这也不起作用。我知道我可能可以将 customView 存储在 UIButton 中并从那里开始,但只是想知道是否可以在这样的消息中进行转换?
I have:
[[[[self navigationItem] leftBarButtonItem] customView] setTitle:@" Create "];
Which is triggering a warning "'UIView' may not respond to '-setTitle:'". I've tried:
[[[[self navigationItem] leftBarButtonItem] (UIButton*)customView] setTitle:@" Create "];
And get errors when I do this. 0I also tried casting with (id) and that didn't work either. I know I could probably just store the customView in a UIButton and go from there, but just wondering if it's possible to cast within a message like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
想想你要铸造什么。试试这个
这一行和您的行的区别在于您不应该强制转换属性(例如
customView
),而应该强制转换您要对其调用方法的返回对象。Think about what you are casting. Try this
The difference in this line and your line is that you should not cast a property (e.g.
customView
) but rather the returned object on which you are about to call a method.如前所述,明智的做法是检查 customView 的具体类或实例是否respondsToSelector,否则如果该特定视图因任何原因发生更改,您可能会遇到崩溃。
否则,使用点符号(所有这些实际上都是属性)进行这种嵌套将使您的代码更具可读性?
Like said earlier, it would be wise to check for the concrete class of customView or if the instance respondsToSelector, otherwise you're likely to experience crashes should that particular view change for whatever reason.
Otherwise, using the dot notation (all of these are actually properties) for this kind of nesting will make your code a lot more readable?