【问题标题】:refreshcontrol endrefreshing has to wait for the subclassrefreshcontrol endrefreshing 必须等待子类
【发布时间】:2013-08-05 11:39:13
【问题描述】:

我为我的 tableview 实现了一个 refreshcontrol,它工作正常。但我想实现调用另一个类执行该类中的过程。我希望我的 refreshcontrol 应该等到该类的执行。

例如:我在 Player 类中有一些数据库更改。现在 refreshcontrol 在数据库更改正在进行时结束刷新。

-(void)pullToRefresh{
    UpdOther *updO = [[UpdOther alloc] initWithProfile:@"Player"];
    [updO release];
    [refreshControl endRefreshing];
}

【问题讨论】:

    标签: ios objective-c pull-to-refresh


    【解决方案1】:

    与其让pullToRefresh 方法等待更新,不如在更新过程中简单地使用一个完成块会更好,这样pullToRefresh 可以告诉更新过程在更新完成后该做什么。

    例如,不是让initWithProfile 执行更新过程,您可以有一些方法,比如performUpdateWithCompletion 执行它,但给它一个完成块:

    - (void)performUpdateWithCompletion:(void (^)(void))completionBlock
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
            // do synchronous update here
    
            // when done, perform the `completionBlock`
    
            if (completionBlock) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completionBlock();
                });
            }
        });
    }
    

    然后您的pullToRefresh 可以指定它希望更新过程在完成后执行的操作,例如:

    - (void)pullToRefresh{
        UpdOther *updO = [[UpdOther alloc] initWithProfile:@"Player"];
        __weak typeof(self) weakSelf = self;
        [updO performUpdateWithCompletion:^{
            typeof(self) strongSelf = weakSelf;
            [strongSelf.refreshControl endRefreshing];
        }];
        [updO release];
    }
    

    还有其他方法(委托模式、通知模式),但我更喜欢基于块的解决方案的内联即时性。


    顺便说一句,如果UpdOther 正在使用NSURLConnectionDataDelegate 方法,您显然需要从其他方法(例如connectionDidFinishLoading)调用completionBlock。因此,在这种情况下,您将在 UpdOther 中定义一个块属性,如下所示:

    @property (nonatomic, copy) void (^updateCompletionBlock)(void);
    

    或者,您可以为此块定义typedef

    typedef void (^UpdateCompletionBlock)(void);
    

    然后在你的属性声明中使用它:

    @property (nonatomic, copy) UpdateCompletionBlock updateCompletionBlock;
    

    无论如何,在这种情况下,您的 performUpdateWithCompletion 会在该属性中保存块的副本:

    - (void)performUpdateWithCompletion:(void (^)(void))completionBlock
    {
        self.updateCompletionBlock = completionBlock;
    
        // now initiate time consuming asynchronous update here
    }
    

    然后,无论您如何完成下载,都可以在此处调用保存的完成块:

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        // do whatever extra steps you want when completing the update
    
        // now call the completion block
    
        if (self.updateCompletionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.updateCompletionBlock();
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多