ncr*_*ins 0 objective-c nsmutablearray ios
我正在尝试构建一个示例应用程序,它从URL中抓取一些json并将其显示在表视图中.我在将数据存储到对象中并将这些对象插入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);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试检查self.movieList中viewDidLoad它具有零个对象,但是当我检查list中 createMovies,我得到六个对象.
我的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"
}
]
Run Code Online (Sandbox Code Playgroud)
AFJSONRequestOperation是异步加载数据.因此,当[错误命名 - 应该只是loadDataFromAPI] getDataFromAPI方法返回时,数据尚未实际加载.
您的createMovies:方法应该触发UI刷新,导致电影显示.