iOS:fix Collection <__NSDictionaryM: XX> was mutated while being enumerated

This commit is contained in:
pengfei.zhou 2020-04-18 14:07:32 +08:00 committed by osborn
parent a386c548ec
commit 4376e37836

View File

@ -21,14 +21,14 @@
@interface DoricNotificationPlugin () @interface DoricNotificationPlugin ()
@property(nonatomic, strong) NSMutableDictionary<NSString *, id> *observers; @property(nonatomic, copy) NSDictionary<NSString *, id> *observers;
@end @end
@implementation DoricNotificationPlugin @implementation DoricNotificationPlugin
- (NSMutableDictionary *)observers { - (NSDictionary *)observers {
if (!_observers) { if (!_observers) {
_observers = [NSMutableDictionary new]; _observers = [NSDictionary new];
} }
return _observers; return _observers;
} }
@ -69,7 +69,9 @@ - (void)subscribe:(NSDictionary *)dic withPromise:(DoricPromise *)promise {
DoricPromise *currentPromise = [[DoricPromise alloc] initWithContext:self.doricContext callbackId:callbackId]; DoricPromise *currentPromise = [[DoricPromise alloc] initWithContext:self.doricContext callbackId:callbackId];
[currentPromise resolve:note.userInfo]; [currentPromise resolve:note.userInfo];
}]; }];
self.observers[callbackId] = observer; NSMutableDictionary *mutableDictionary = [self.observers mutableCopy];
mutableDictionary[callbackId] = observer;
self.observers = mutableDictionary;
[promise resolve:callbackId]; [promise resolve:callbackId];
} }
@ -77,16 +79,18 @@ - (void)unsubscribe:(NSString *)subscribeId withPromise:(DoricPromise *)promise
id observer = self.observers[subscribeId]; id observer = self.observers[subscribeId];
if (observer) { if (observer) {
[[NSNotificationCenter defaultCenter] removeObserver:observer]; [[NSNotificationCenter defaultCenter] removeObserver:observer];
[self.observers removeObjectForKey:subscribeId]; NSMutableDictionary *mutableDictionary = [self.observers mutableCopy];
[mutableDictionary removeObjectForKey:subscribeId];
self.observers = mutableDictionary;
} }
[promise resolve:nil]; [promise resolve:nil];
} }
- (void)dealloc { - (void)dealloc {
[self.observers enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) { NSDictionary *dictionary = self.observers;
[dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
[[NSNotificationCenter defaultCenter] removeObserver:obj]; [[NSNotificationCenter defaultCenter] removeObserver:obj];
}]; }];
[self.observers removeAllObjects];
} }
@end @end