将参数传递给一个块?

时间:2012-08-31 16:40:48

标签: iphone objective-c ios cocoa-touch objective-c-blocks

我有一个单例,我用它来解析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

1 个答案:

答案 0 :(得分: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);
}