2011-08-12 26 views
1

我想以下幾點:NSNotificationCenter,塊和SEL類型的實例變量:不能得到它的工作

每當OAuth憑證的變化,我想更新我的一些看法控制器。我想要更新的視圖控制器都從視圖控制器繼承。無論何時設置新的訪問令牌或訪問令牌被清除時,此視圖控制器都將監聽通知。無論何時設置或清除訪問令牌,我都希望將選擇器設置爲在顯示視圖控制器時應執行的方法(即在-viewWillAppear:上)。

不知何故addObserverForName:object:queue:usingBlock:內部的塊似乎並沒有被調用。我無法將其記錄到日誌中。正因爲如此,選擇者從不改變。根據我讀過的文章,使用伊瓦爾的__block屬性應該允許從一個區塊內改變伊娃。

@interface SDViewController() 
- (void)reloadData; 
- (void)clearData; 
@end 


@implementation SDViewController 
{ 
    __block SEL selectorOnViewWillAppear; 
} 

- (id)initWithDataSource:(id <SDViewControllerDataSource>)dataSource 
{ 
    self = [super init]; 
    if (self) 
    { 
     selectorOnViewWillAppear = @selector(reloadData); 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    NSLog(@"view did load"); 

    [super viewDidLoad]; 

    [[NSNotificationCenter defaultCenter] addObserverForName:kAccessTokenChangedNotification object:self queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) { 
     NSLog(@"selector: test1"); 
     selectorOnViewWillAppear = @selector(reloadData); 
    }]; 
    [[NSNotificationCenter defaultCenter] addObserverForName:kAccessTokenClearedNotification object:self queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) { 
     NSLog(@"selector: test2"); 
     selectorOnViewWillAppear = @selector(clearData); 
    }]; 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 

    if (selectorOnViewWillAppear) 
     [self performSelector:selectorOnViewWillAppear]; 
} 

- (void)reloadData 
{ 
    NSLog(@"reloadData"); 
    selectorOnViewWillAppear = nil; 
} 

- (void)clearData 
{ 
    NSLog(@"clearData"); 
    selectorOnViewWillAppear = nil; 
} 

@end 
+1

鑑於塊永遠不會被處理,你是積極的代碼,觸發通知是這樣做適當? –

+0

似乎通知沒有被調用,但我無法弄清楚這是什麼原因。我打算再看看代碼... –

+1

這就是我的意思。也許開始的一個好地方就是你實際發佈通知的地方(*,因爲這是等式的另一邊),並從那裏開始工作。如果你想在這裏發佈代碼,我很樂意看看。 –

回答

0

從這個不斷變化的觀測碼固定它:

[[NSNotificationCenter defaultCenter] 
    addObserverForName:kAccessTokenClearedNotification 
    object:self 
    queue:[NSOperationQueue currentQueue] 
    usingBlock:^(NSNotification *note) { 
     NSLog(@"selector: test2"); 
     selectorOnViewWillAppear = @selector(clearData); 
    }]; 

要這樣:

[[NSNotificationCenter defaultCenter] 
    addObserverForName:kAccessTokenClearedNotification 
    object:nil 
    queue:[NSOperationQueue currentQueue] 
    usingBlock:^(NSNotification *note) { 
     NSLog(@"selector: test2"); 
     selectorOnViewWillAppear = @selector(clearData); 
    }]; 

與此相關的問題is found here蘋果文檔。方法中的對象應該是生成通知的對象。將對象設置爲nil解決了問題。