2012-08-31 177 views
1

我有一個單例,我用它來解析XML然後緩存它。解析/緩存是通過一個塊完成的。有沒有辦法讓我從另一個類傳遞參數給這個塊,這樣我就可以從單身之外更改URL了?將參數傳遞給塊?

這裏是我現在的代碼:

// The singleton 
+ (FeedStore *)sharedStore 
{ 
    static FeedStore *feedStore = nil; 
    if(!feedStore) 
     feedStore = [[FeedStore alloc] init]; 

    return feedStore; 
} 

- (RSSChannel *)fetchRSSFeedWithCompletion:(void (^)(RSSChannel *obj, NSError *err))block 
{ 
    NSURL *url = [NSURL URLWithString:@"http://www.test.com/test.xml"]; 

    ... 

    return cachedChannel; 
} 

這裏的地方我需要從修改NSURL類:

- (void)fetchEntries 
{ 
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 

    // Initiate the request... 

    channel = [[BNRFeedStore sharedStore] fetchRSSFeedWithCompletion: 
      ^(RSSChannel *obj, NSError *err) { 
     ... 
    } 
} 

我如何通過從fetchEntriesfetchRSSFeedWithCompletion的說法?

回答

4

你會想在方法中添加一個參數,而不是塊。

此外,當使用完成塊時,確實沒有理由返回方法中的任何內容。

我會改變它看起來像這樣:

-(void)fetchRSSFeed:(NSURL *)rssURL completion:(void (^)(RSSChannel *obj, NSError *error))block{ 
    RSSChannel *cachedChannel = nil; 
    NSError *error = nil; 

    // Do the xml work that either gets you a RSSChannel or an error 

    // run the completion block at the end rather than returning anything 
    completion(cachedChannel, error); 
} 
+0

真棒,謝謝!仍然學習塊如何工作,所以不知道如何修改該方法:) – bmueller

+0

該代碼似乎沒有修改返回線在最後工作正常 - 是否有任何特殊的原因,我應該補充說,完成(cachedChannel,錯誤) ;'而不是隻是返回'cachedchannel'? – bmueller

+1

對一個人來說是多餘的。如果你的xml在後臺被解析(它應該是),你也可能遇到一些問題。 – jordanperry