在 Objective-C 中发送消息时可以强制转换吗?

发布于 2024-12-11 12:08:01 字数 392 浏览 0 评论 0原文

我有:

[[[[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧街凉风 2024-12-18 12:08:01

想想你要铸造什么。试试这个

[(UIButton*)[[[self navigationItem] leftBarButtonItem] customView] setTitle:@" Create "];

这一行和您的行的区别在于您不应该强制转换属性(例如 customView),而应该强制转换您要对其调用方法的返回对象。

Think about what you are casting. Try this

[(UIButton*)[[[self navigationItem] leftBarButtonItem] customView] setTitle:@" Create "];

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.

葬花如无物 2024-12-18 12:08:01

如前所述,明智的做法是检查 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文