[英]Can not remove NotificationCenter observer inside protocol extension
[英]Remove observer or find a better alternative to NotificationCenter ios
我有一些關於NSNotification及其觀察者生命周期的問題。
UPD。
我將簡化我的應用程序的邏輯,因此它看起來很原始:
ViewController A有一個按鈕“ Comment”,還包含一個UIViewB。在這個UIView上,我們還有另一個按鈕“ Share”。 如果用戶已登錄,則每個按鈕都會執行應有的操作,否則,它將從NSObject類“ Logistic”(其中邏輯最多的地方)中調用“ login”方法,並顯示彈出視圖C。 因此,我在C語言中創建了一個postNotificationName,以使按鈕在用戶登錄時進行監聽-完成其工作。
例如在viewController A
- (void) comment{
if (<user_logged_in>){
//do the magic
[self removeObserver];
} else {
[self removeObserver];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(comment) name:@"dismiss_popup" object:nil];
[Logistic login];
}
}
我對“共享”方法(在視圖B中)執行相同的操作,但是例如當我按下按鈕“注釋”,然后跳過C-登錄彈出窗口時,然后按“共享”按鈕,進行登錄-之后,“共享”和“評論” 將同時開始其操作 。
我想我應該打電話給removeObserver
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"dismiss_popup" object:nil];
但是,當它仍然存在時,如何在UIView B中進行呢?
問候 。
您可以在物流中修改您的登錄方法,如下所示:
功能原型:
+ (void)loginComplete:(void(^)(BOOL success))complete;
功能本身:
+ (void)loginComplete:(void(^)(BOOL success))complete {
//login code
BOOL success = YES;//or no if it was some problems))
complete(success);//replace notification post with this
}
最后是您的viewController A:
- (void) comment{
if (<user_logged_in>){
//do the magic
[self removeObserver];
} else {
[self removeObserver];
//we don't need Notification center anymore
[Logistic loginСomplete:^(BOOL success) {
handle login completion
}];
}
}
- (IBAction)commentButton:(id)sender {
if (!user logged in) {
[self.logistic loginUserWithCompletion:^(id result){
if (![result isKindOfClass:[NSError class]]) {
[self doStuff];
}
}];
} else {
[self doStuff];
}
重述您的問題:
我建議讓A處理與C的所有通信,因此,如果B需要與C通話,則需要通過A。這是您可以執行的操作:
在UiViewController A中
-(void) viewDidLoad{
//Adding a notification listener should be done in initialization stage.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(dismissViewC:)
name:@"dismiss_popup" object:nil];
}
- (void) comment{
if (<user_logged_in>){
//proceed with comment
} else {
NSNumber* caller=[NSNumber numberWithInt:COMMENT];
[Logistic login:caller];
}
}
-(void) dismissViewC:(NSNotification*) notify{
(NSNumber*) callerId =[notify object];
switch(callerId.intValue){
case COMMENT: //proceed with comment;
case: SHARE: [self.viewB share];
}
}
-(void) dealloc {
// removing an observer should be done in the dealloc stage
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
在UIView B中:
- (void) share{
if (<user_logged_in>){
//proceed with share
} else {
NSNumber* caller=[NSNumber numberWithInt:SHARE];
[Logistic login:caller];
}
}
物流將需要將新的登錄參數傳遞給C,C看起來像這樣:
-(void) login:(NSNumber*) caller{
self.myCaller=caller;
// proceed with login
}
-(void) dismissMe{
[[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss_popup"
object:self.caller];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.