IOS,删除警告?

时间:2011-09-06 14:29:31

标签: objective-c ios uiviewcontroller

我正在尝试从此行中删除警告:

UIViewController * appController = [[[UIApplication sharedApplication] delegate]     viewController];

我对这行代码的警告如下: “找不到实例方法'viewController'(返回类型默认为'id')

有人可以帮助解释我如何消除这种渐弱的消失吗?

非常感谢,

4 个答案:

答案 0 :(得分:3)

您需要转换应用程序委托:

UIViewController * appController = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] viewController];

答案 1 :(得分:1)

向您的委托添加演员:

UIViewController * appController = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] viewController];

答案 2 :(得分:1)

我不知道你的...AppDelegate是如何被调用的,所以我在这里使用DemoAppDelegate

UIViewController *appController = [(DemoAppDelegate *)[[UIApplication sharedApplication] delegate] viewController];

答案 3 :(得分:0)

类型转换是嘈杂的,可能很危险。为了解决这个问题,我通常最终会创建一个简单的类方法。假设该类总是打算用作app委托,你可以这样写:

// MONApplicationDelegate.h
@interface MONApplicationDelegate : NSObject < UIApplicationDelegate >

// ...

+ (MONApplicationDelegate *)sharedApplicationDelegate;
- (UIViewController *)viewController;

@end

// MONApplicationDelegate.m
@implementation MONApplicationDelegate

// ...

+ (MONApplicationDelegate *)sharedApplicationDelegate
{
    id ret = [[UIApplication sharedApplication] delegate];
    if (nil == ret) {
        assert(0 && "oops - app delegate has not been created yet");
        return nil;
    }
    if (![ret isKindOfClass:[MONApplicationDelegate class]]) {
        assert(0 && "invalid class type for shared application delegate");
        return nil;
    }
    else {
        return ret;
    }
}

@end

// in action
UIViewController * appController =
  [[MONApplicationDelegate sharedApplicationDelegate] viewController];

// which is shorter and safer to use, when compared to:
UIViewController * appController =
  [(MONApplicationDelegate*)[[UIApplication sharedApplication] delegate] viewController];