我正在尝试在一个项目中使用它:https://github.com/zakkhoyt/VWWPermissionKit
我不太了解 KVO/Notification Center,所以发布了一个问题。
权限管理器的 init 和 dealloc 基本上是这样的:
- (instancetype)init {
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserverForName:VWWPermissionNotificationsPromptAction object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
dispatch_async(dispatch_get_main_queue(), ^{
VWWPermission *permission = note.userInfo[VWWPermissionNotificationsPermissionKey];
[permission presentSystemPromtWithCompletionBlock:^{
dispatch_async(dispatch_get_main_queue(), ^{
[permission updatePermissionStatus];
if(permission.status == VWWPermissionStatusDenied){
[self.permissionsViewController displayDeniedAlertForPermission:permission];
}
[self checkAllPermissionsSatisfied];
});
}];
});
}];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
dispatch_async(dispatch_get_main_queue(), ^{
[self readPermissions];
});
}];
}
return self;
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
如果我想读取一组权限,我会调用它:
NSArray *permissionsToRead = @[
[VWWCoreLocationWhenInUsePermission permissionWithLabelText:nil],
[VWWNotificationsPermission permissionWithLabelText:nil]
];
[VWWPermissionsManager readPermissions:permissionsToRead resultsBlock:^(NSArray *permissions) {
// Do something with the result
}
}];
一切正常。问题是没有调用 dealloc,因此仍在调用通知,例如在 init 方法中创建的 UIApplicationDidBecomeActiveNotification
。
据我所知,权限管理器已创建但未被引用,因此它只是挂起。
readPermssions 的公共(public)方法如下:
+(void)readPermissions:(NSArray*)permissions resultsBlock:(VWWPermissionsManagerResultsBlock)resultsBlock{
VWWPermissionsManager *permissionsManager = [[self alloc]init];
[permissionsManager readPermissions:permissions resultsBlock:resultsBlock];
}
创建一个新实例并调用另一个方法,然后将 resultsBlock 传回。据我所知,没有任何东西可以释放它。我将如何调用 dealloc?
最佳答案
这是因为 NSNotificationCenter
保留了观察者对象,它保留了向它注册的 block ,它捕获了你的 View Controller 并防止它被释放。
如果你希望你的 View Controller 能够被释放,那么你应该在 block 外创建一个弱引用(__weak typeof(self) weakSelf = self;
)并使用 block 内的 weakSelf
。
您也没有正确移除观察者。当您使用通知中心 block api 添加观察者时,它会返回一个对象,该对象实际上是作为观察者添加的对象,您需要保留对它的引用并将其传递给 removeObserver:
。
我建议不要使用 block 观察方法,因为它增加了比其值(value)更多的管理麻烦。请改用带有选择器的那个。
关于ios - 导致没有 dealloc 被调用的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31866454/