ODWeakify
使用方法
您是否经常在 ObjC 中编写类似的内容?
__weak __typeof(self) weakSelf = self;
self.completionHandler = ^{
__typeof(self) strongSelf = weakSelf;
[strongSelf doSomething];
// or just use weakSelf
weakSelf.var = nil;
// some other code
self.property = @"foo";
};
看起来很糟糕。你有注意到,我们在设置 foo 时忘记使用 weakSelf,这是一个常见的错误。所以,使用 ODWeakify 可以更容易地做到这一点
// #import <ODWeakify.h>
od_weakify(self);
self.completionHandler = ^{
od_strongify(self);
[self doSomething];
self_weak_.var = nil; // We can still use weak if we need it
self.property = @"foo";
};
现在,block 中的所有 self
都会安全地防止 retain 循环。如果你忘记使用强引用(并且不会使用 self_weak_),你会得到一个警告。
安装
ODWeakify 支持多种方法将库安装到项目。
使用 CocoaPods 进行安装
CocoaPods 是 Objective-C 和 Swift 项目的依赖管理器,可以自动化和简化使用第三方库(如 ODWeakify)的过程。您可以使用以下命令安装它:
$ gem install cocoapods
Podfile
要使用CocoaPods将ODWeakify集成到您的Xcode项目中,请在您的Podfile
中指定它。
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
target 'TargetName' do
pod 'ODWeakify'
end
然后,运行以下命令:
$ pod install
使用Carthage进行安装
Carthage 是一个去中心化的依赖管理器,它可以构建您的依赖并为您提供二进制框架。
您可以使用以下命令通过 Homebrew 安装Carthage:
$ brew update
$ brew install carthage
要使用Carthage将ODWeakify集成到您的Xcode项目中,请在您的Cartfile
中指定它。
github "Rogaven/ODWeakify" ~> 1.1
运行 carthage
以构建框架,然后将构建的 ODWeakify.framework
拖到您的Xcode项目中。
作者
Alexey Nazarov, [email protected]
许可证
ODWeakify在MIT许可证下提供。有关更多信息,请参阅LICENSE文件。