2013-01-13 50 views
0

我試圖構建一個示例應用程序,它從url獲取一些json並將其顯​​示在表視圖中。我有一個問題,將數據存儲到一個對象中,並將這些對象插入到NSMutableArray中。將對象存儲到NSMutableArray中

TableView.m

- (void) getDataFromAPI { 
    NSString *endpoint = @"http://www.somesite.com/list.php"; 

    NSURL *url = [NSURL URLWithString:endpoint]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 


    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
     [self createMovies: JSON]; 
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response , NSError *error , id JSON){ 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Uh oh, there's been a problem!" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil]; 
     [alert show]; 
    }]; 
    [operation start]; 
} 

- (void) createMovies: (id) json { 

    NSMutableArray *list = [[NSMutableArray alloc] init]; 
    for (id entry in json) { 
     Movie *aMovie = [[Movie alloc] init]; 
     aMovie.movieId = [entry objectForKey:@"id"]; 
     aMovie.title = [entry objectForKey:@"title"]; 
     aMovie.director = [entry objectForKey:@"director"]; 
     aMovie.price = [entry objectForKey:@"price"]; 

     aMovie = nil; 
    } 
    NSLog(@"%@", list); 
    self.movieList = list; 
} 

- (void)viewDidLoad 
{ 
    self.movieList = [[NSMutableArray alloc] init]; 
    [super viewDidLoad]; 

    [self getDataFromAPI]; 
    self.title = @"Movies"; 


    NSLog(@"%@", self.movieList); 
} 

當我嘗試檢查self.movieListviewDidLoad它具有零個對象,但是當我在createMovies檢查list我得到六個對象。

的json數據的例子:

[ 
    { 
    "id": 1, 
    "title": "Transformers", 
    "price": 29.54, 
    "Director": "Michael Bay" 
    }, 
    { 
    "id": 2, 
    "title": "South Park", 
    "price": 34.88, 
    "author": "Matt Stone, Trey Parker" 
    }, 
    { 
    "id": 3, 
    "title": "The Hobbit", 
    "price": 20.04, 
    "author": "Peter Jackson" 
    } 
] 
+0

那麼,你的請求是異步的... –

回答

5

AFJSONRequestOperation異步加載數據。所以,當[錯誤地命名 - 應該只是loadDataFromAPI] getDataFromAPI方法已返回時,數據尚未實際加載。

您的createMovies:方法應觸發導致電影顯示的UI刷新。

+0

我甚至沒有把它粘到UI上,所以UI刷新不會幫助我不這麼認爲。 – ncremins

+3

雖然同樣的問題。您在加載之前異步加載某些內容並打印出結果。 – bbum

+0

但在AFJSONRequestionOperation中,我在成功方法中調用createMovies,這是否意味着請求已異步完成加載? – ncremins

相關問題