objective-c - 为什么这个 UIButton/IBAction 不刷新我的页面?

标签 objective-c ios json ios5 uibutton

当我加载主视图时,它会自动加载包含博客文章的 JSON 提要。

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

当我单击刷新按钮时,我试图让 View 重新加载 JSON feed,但这不起作用。

我做错了什么?

我的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];
        });
    });
}
...

最佳答案

该帖子没有按照您的预期进行更新,因为它是在异步 block 内捕获的。如果我没记错的话,实例变量一旦传递到 block 中就会被复制,因此对它们的更改不会反射(reflect)在异步 block 之外,除非它们具有 __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];
        });
    });
}

关于objective-c - 为什么这个 UIButton/IBAction 不刷新我的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12700560/

相关文章:

iphone - UITableView ,重新加载时滚动到底部?

ios - 将数据传递给 UICollectionReusableView

objective-c - 旋转和捏合(缩放)手势会扰乱父 UIView 及其 subview 框架

c++ - Qt 中的 Objective-C with Mavericks

iOS - 使用自动布局执行多个同步动画

ios - 如何将高分保存并打印到下一个场景?

ios - 设置 Google Analytics iOS Swift

mysql - 在 Sencha Architect 中将 MySql 查询检索到 JSON - 如何?

php - 如何用 json 回显数组?

javascript - 使用 jquery 基于值的 JSON 迭代