When I load my Master View it automatically loads a JSON feed with blog posts.
I have a refresh button on the top bar of my Master View. I have already connected it successfully to an IBAction and when clicked, I can output a string to log.
I am trying to get my view to reload the JSON feed when I click on the refresh button but that doesn’t work.
What am I doing wrong?
My ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UICollectionViewController {
NSArray *posts;
}
- (void)fetchPosts;
- (IBAction)refresh:(id)sender;
@end
My 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];
});
});
}
...
The post is not being updated as you expect as it is being captured inside of the async block. If I remember correctly, instance variables are copied once passed into a block, so changes to them aren’t reflected outside of the async block unless they have the
__blockmodifier.Try this,