2011-03-18 105 views
0

好的 - 這個很奇怪。我有一個從XML文件加載信息的單例類。我使用的是委託定義如下(我定義在一個單獨的頭文件中的代表,使生活更輕鬆):奇怪的自定義代理操作

@protocol ResourceClassDelegate <NSObject> 

@optional 
- (void)picturesDidStartLoading; 
- (void)picturesDidFinishLoading; 
@end 

在資源文件,委託正確定義(我相信):

@property (assign) id<ResourceClassDelegate> delegate; 

當使用代理,在資源類中的代碼如下:

-(void)refreshPiecesOfHistoryWithOperation { 

    NSLog(@"Operation Started"); 
    if ([delegate respondsToSelector:@selector(picturesDidStartLoading)]) 
     [delegate picturesDidStartLoading]; 

    self.picturePacks = [HistoryXMLParser loadPicturePacks]; 

    [self.allPiecesOfHistory removeAllObjects]; 

    // now lets put all of them in one big file... 
    for (PicturePack *pp in self.picturePacks) { 
     for (int ct = 0; ct < [[pp piecesOfHistory] count] ; ct++) { 
      [self.allPiecesOfHistory addObject:(PieceOfHistory *)[[pp piecesOfHistory] objectAtIndex:ct]];   
     } 
    } 

    NSLog(@"Operation Ended"); 
    if ([delegate respondsToSelector:@selector(picturesDidFinishLoading)]) 
     [delegate picturesDidFinishLoading]; 

} 

現在......在監聽到委託類,它被分配:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // now for the part that makes the loading all happen... 
    [[ResourceClass sharedResourceClass] setDelegate:self]; 
} 

而且在聽力課,被定義的方法....

#pragma mark ResourceClassDelegate 
-(void)picturesDidStartLoading { 

    if (loadingActivity == nil) 
     loadingActivity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; 

    [self.view addSubview:loadingActivity]; 
    [loadingActivity setCenter:[self.view center]]; 
    [loadingActivity startAnimating]; 

} 

-(void)picturesDidFinishLoading { 

    if (loadingActivity != nil) { 
     [loadingActivity stopAnimating]; 
     [loadingActivity removeFromSuperview]; 
    } 

    [self.tableView reloadData]; 
} 

現在的問題......每一次,在聽力課,方法(無效)picturesDidFinishLoading是調用。方法(void)picturesDidStartLoading永遠不會被調用。

當我調試的代碼,在資源類,行

if ([delegate respondsToSelector:@selector(picturesDidStartLoading)]) 
    [delegate picturesDidStartLoading]; 

從未達到的委託方法調用 - 即使我刪除if語句。該行

if ([delegate respondsToSelector:@selector(picturesDidFinishLoading)]) 
    [delegate picturesDidFinishLoading]; 

總是被調用。

有什麼想法?

回答

0

這很奇怪,請嘗試刪除協議聲明中的@optional,並查看是否收到某些警告。

嘗試在方法中打印日誌,除了它看起來不錯。

+0

良好的通話....去除@optional之後 - 沒有錯誤或警告。然後,我評論了那些沒有工作和編譯的方法 - 有適當的警告。 – 2011-03-18 22:32:02

+0

您是否在函數中添加了NSLog以確保它沒有被調用? – Idan 2011-03-18 22:35:21

+0

是的 - 沒有被調用 - 我在活動指標線之上添加了它。 – 2011-03-18 22:36:48

1

好的 - 我想通了......

代表在第一次通話期間是零。它是nil的原因是因爲在init方法期間使用委託的函數在源代碼中被調用。在執行委託的第一個測試時,init方法未完成。此時該委託爲零,因爲它在init方法完成之前未被實例化。委託人第二次測試的原因是因爲我使用NSOperationQueue提交了過程。

要解決這個問題,我必須將問題轉移一點......這是關於時間安排!

現在好了,這很有趣....