为什么这个UIButton / IBAction没有刷新我的页面?

时间:2012-10-03 00:56:15

标签: objective-c ios json ios5 uibutton

当我加载主视图时,它会自动加载带有博客帖子的JSON提要。

我的主视图顶部栏上有一个刷新按钮。我已将其成功连接到IBAction,点击后,我可以输出一个字符串进行记录。

当我点击刷新按钮时,我试图让我的视图重新加载JSON提要,但这不起作用。

我做错了什么?

我的ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UICollectionViewController {
    NSArray *posts;
}

- (void)fetchPosts;

- (IBAction)refresh:(id)sender;
@end

我的ViewController.m

...

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self fetchPosts];
}

- (IBAction)refresh:(id)sender {

    [self fetchPosts];
}

- (void)fetchPosts
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString: @"http://website.com/app/"]];

        NSError* error;

        posts = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
    });
}
...

1 个答案:

答案 0 :(得分:2)

该帖子未按预期更新,因为它是在异步块内捕获的。如果我没记错的话,实例变量一旦被传递到一个块就会被复制,所以对它们的更改不会反映在异步块之外,除非它们具有__block修饰符。

试试这个,

- (void)fetchPosts
{
    __block NSArray *blockPosts = posts;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString: @"http://website.com/app/"]];

        NSError* error;

        blockPosts = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
    });
}
相关问题