[英]Pass argument to a block?
我有一個單例,我用來解析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) {
...
}
}
如何將參數從fetchEntries
給fetchRSSFeedWithCompletion
?
您可能希望在方法中添加參數,而不是塊。
此外,使用完成塊時,確實沒有理由在方法中返回任何內容。
我把它改成這樣:
-(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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.