MethodNotificationCenter 0.1.1

MethodNotificationCenter 0.1.1

Joseph Newton 维护。



  • 作者:
  • Joseph Newton

MethodNotificationCenter

Objective-C 运行时注入

Codacy Badge License MIT CocoaPods Compatible Carthage Compatible Platform Code Coverage

Swift Package Xcode Project Cocoapods Carthage

MethodNotificationCenter 是一个轻量级的框架,用于在 iOS、macOS 和 tvOS 上进行 Objective-C 运行时方法注入。

目的

该库的目的是为了能够探索和理解 Objective-C 运行时及其提供的 Apple 库中的方法/API 的复杂性。

该库可以在一个特定对象调用给定方法之前和之后通知您,其方式非常类似于 Foundation 的 NSNotificationCenter

请注意,此库仅供
**教育目的**。该库运行的机制不仅使其易变且不适合生产版本,而且使用它可能无法通过 Apple App Store 的审核(未经测试)。

安装

MethodNotificationCenter 通过 CocoaPodsCarthageSwift Package Manager 提供。

要使用 CocoaPods 安装,只需将以下行添加到 Podfile 中

pod 'MethodNotificationCenter'

要使用 Carthage 安装,请将以下行添加到 Cartfile 中

github "SomeRandomiOSDev/MethodNotificationCenter"

要使用 Swift Package Manager 安装,请将以下行添加到 Package.swift 文件的 dependencies

.package(url: "https://github.com/SomeRandomiOSDev/MethodNotificationCenter.git", from: "1.0.0")

使用方法

首先在源文件顶部导入 MethodNotificationCenter

Cocoa

@import MethodNotificationCenter;

Swift

import MethodNotificationCenter

导入后,只需使用 +[MethodNotificationCenter addObserverForSelector:object:callback:] 来注册一个方法调用的拦截块处理器

Cocoa

...
id observable = [MethodNotificationCenter addObserverForSelector:@selector(objectAtIndex:) object:array callback:^(MethodNotification *notification) {
    NSLog(@"NSArray's `objectAtIndex:` method was called");
}];

Swift

...
let observable = MethodNotificationCenter.addObserver(for: #selector(NSArray.objectAtIndex(_:)), object:nsarray) { notification in
    print("NSArray's `objectAtIndex:` method was called")
}

现在,您的回调块会在已指定的对象上每次调用给定选择器之前和之后被调用。完成拦截后,只需将注册方法返回的值传递给 +[MethodNotificationCenter removeObserver:]

Cocoa

...
[MethodNotificationCenter removeObserver:observable];

Swift

...
MethodNotificationCenter.removeObserver(observable)

限制

这个库的能力有一些显著的限制

  • 方法通知不是递归发送的。也就是说,您会收到给定方法的“顶级”调用通知,但如果该方法(或其内部任何方法调用)调用相同的该方法,则不会发送该通知。
  • 由于 Swift 编译器进行的优化,Swift 中的 Swift 方法调用(但注解了 @objc 属性)通常由编译器硬编码,并且不使用 Objective-C 运行时,这阻止了通知的发送。从 Swift 调用 Objective-C 类(反之亦然)不应出现此问题。有关示例,请参阅 Tests/MethodNotificationCenterTests/MethodNotificationCenterSwiftTests/MethodNotificationCenterTests.swift

贡献

如果您需要特定的功能或遇到错误,请打开一个问题。如果您自己扩展了 MethodNotificationCenter 的功能或认为自己可以修复错误,请提交一个拉取请求。

作者

Joe Newton,[email protected]

许可证

方法通知书中心 可在 MIT 许可下使用。更多信息请参阅 许可证 文件。