当我加载主视图时,它会自动加载包含博客文章的 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/