2012-10-03 54 views
2

當我加載我的主視圖時,它會自動加載包含博客文章的JSON供稿。爲什麼這個UIButton/IBAction不能刷新我的頁面?

我在主視圖的頂部欄上有一個刷新按鈕。我已經成功將它連接到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]; 
     }); 
    }); 
} 
... 
+0

是否成功下載數據? – DrummerB

+0

你想更新UILabel嗎?你的UILabel在哪裏?它在另一個視圖控制器中嗎?你想刷新整個視圖控制器嗎?視圖控制器在切換到另一個時進行「刷新」。 – stackOverFlew

+0

您正在嘗試重新加載視圖而不實際重新加載它? collectionView是否已成功連接到接口構建器引用插座的UITableView?請提供更多信息和更多的代碼。 – stackOverFlew

回答

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]; 
        }); 
    }); 
} 
+0

Thanks @holex :) – haroldcampbell

+0

harold so this代碼將被調用初始加載並在一次點擊刷新時調用?或者它應該是特定的刷新? – pepe

+0

是的。它被稱爲初始加載,並且每當有人點擊刷新按鈕... ...恕我直言 – haroldcampbell

相關問題