(AppDelegate *) 的含义
有人可以解释以下代码片段中的 (AppDelegate *)
是什么意思吗?
(AppDelegate *)[[UIApplication sharedApplication] delegate] iPad]
Can someone explain what (AppDelegate *)
in the following snippet means?
(AppDelegate *)[[UIApplication sharedApplication] delegate] iPad]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
[[UIApplication sharedApplication] delegate]
返回一个id
。因此您无法访问它的例如window
属性(因为 id 对象没有它)。(AppDelegate *)
语句会将id
“转换”为AppDelegate
对象,以便您可以访问其组件。这就像拥有
NSObject *obj1;
和NSString *obj2;
- 你不能使用obj1
执行-substringToIndex:
>...[[UIApplication sharedApplication] delegate]
returns anid
. So you can't access e.g.window
property of it (because id object doesn't have it).(AppDelegate *)
statement causes to 'convert'id
toAppDelegate
object, so you can access its components.It's like having
NSObject *obj1;
andNSString *obj2;
- you can't do-substringToIndex:
withobj1
...该代码将
[[UIApplication sharedApplication] delegate]
的返回值转换为AppDelegate *
类型。这并不是绝对必要的,但当您在可能不支持该方法调用的类上调用方法
iPad
时,它可以防止编译器发出警告。当然,假设AppDelegate
有一个名为iPad
的方法。That code is casting the return value of
[[UIApplication sharedApplication] delegate]
to the typeAppDelegate *
.This is not strictly necessary, but it will prevent compiler warnings when you call the method
iPad
on a class that may not support that method call. Assuming, of course, thatAppDelegate
has a method callediPad
.委托方法返回一个id(一个未分类的对象),因此编译器没有关于返回的对象的信息,特别是不知道它是否有iPad方法。这没关系,但它让事情变得有点模糊(动态类型)。通过将返回的对象显式转换为 AppDelegate 类,您可以告诉编译器您知道返回的委托对象是 AppDelegate 实例。这允许编译器检查您的 AppDelegate 类是否具有 iPad 方法(静态类型)。这很好,因为现在编译器可以进行更准确的错误检查。不过,编译器只是相信你的强制转换,所以不要撒谎!如果您撒谎,并将
iPad
消息发送到没有具有 iPad 方法的对象,您的应用程序可能会在运行时崩溃。The delegate method returns an id (an unclassed object), so the compiler has no information about the object returned, and in particular doesn't know whether it has an iPad method. This is okay, but it leaves things sort of vague (dynamic typing). By casting the returned object explicitly to the AppDelegate class, you're telling the compiler that you know that the returned delegate object is an AppDelegate instance. This allows the compiler to check that your AppDelegate class does have an iPad method (static typing). This is good, because now the compiler can do more accurate error-checking. The compiler just believes your cast, though, so don't lie! If you do lie, and send the
iPad
message to an object that does not have an iPad method, your app can crash at runtime.它只是一个类,用于将委托强制转换为
AppDelegate
It is simply the class, and is used to cast the delegate to
AppDelegate