【问题标题】:Why doesn't this UIButton / IBAction refresh my page?为什么这个 UIButton / IBAction 不刷新我的页面?
【发布时间】:2012-10-03 00:56:15
【问题描述】:

当我加载我的主视图时,它会自动加载带有博客文章的 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];
        });
    });
}
...

【问题讨论】:

  • 数据下载成功了吗?
  • 您要更新 UILabel 吗?你的 UILabel 在哪里?它在另一个视图控制器中吗?您是否尝试刷新整个视图控制器?当您切换到另一个控制器时,查看控制器正在“刷新”。
  • 您正在尝试重新加载视图而不实际重新加载它? collectionView 是成功连接到接口构建器引用插座的 UITableView 吗?请提供更多信息和更多代码。
  • @DrummerB - 我看不到,因为页面内容保持不变,尽管有新条目
  • @user1392515 - 不,尝试更新显示在主视图中的整个 collectionView - 重新加载 MasterView 就可以了

标签: objective-c ios json ios5 uibutton


【解决方案1】:

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

【讨论】:

  • harold 所以这个代码会在初始加载时调用,并在单击刷新时调用?还是应该针对刷新?
  • 是的。它被称为初始加载,并且每当有人单击刷新按钮时......恕我直言
  • 您的代码在第 3 行抛出解析器错误 (__block...) -- incompatible pointer types initializing NSJSONSerialization *__strong with an expression
  • 很抱歉。我通过将__block 变量的类型更改为NSArray 来更新代码;这是基于您的 posts 变量是一个数组的假设。对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2023-03-20
  • 1970-01-01
  • 2021-10-24
相关资源
最近更新 更多