扩展 UIApplicationDelegate 协议

Extending UIApplicationDelegate Protocol

我想扩展 UIApplicationDelegate 协议并为 application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool 方法提供默认实现。但是,我提供的默认实现不会被调用。

是否有可能扩展 UIApplicationDelegate 协议(关于 UIApplication 是单例,或者协议方法是可选的),还是我做错了什么?

感谢

AppDelegate.swift:

import UIKit
extension UIApplicationDelegate{
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        print("does not print anything on launch.")
        return true
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
}

协议扩展没有用。
原因是:

  1. Protocol contains only function declaration but extension needs function definition.
  2. Protocol is nothing but just set of rules(methods). It doesn't allocate any memory.
  3. Protocol function definitions will be in delegate class. So function call will never comes to function definition which you written in extension.

事实证明您无法通过扩展为 Objective-C 协议提供默认实现。有关协议扩展限制的详细列表,请参阅下文 link。

https://www.captechconsulting.com/blogs/ios-9-tutorial-series-protocol-oriented-programming-with-uikit

What we CAN'T do: Provide default implementations for Objective-C protocols.

我 运行 遇到了同样的问题,对于这个特定的文件,我恢复到 Objective-C 来实现这个功能。

#import <UIKit/UIKit.h>

@interface NSObject (BasicMethods) <UIApplicationDelegate>

@end

#import "UIApplicationDelegate+BasicMethods.h"

@implementation NSObject (BasicMethods)

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    NSLog(@"I'm getting called");
}

@end

有效。