ios - 将对象存储到 NSMutableArray

标签 ios objective-c nsmutablearray

我正在尝试构建一个示例应用程序,它从 url 中获取一些 json 并将其显示在表格 View 中。我在将数据存储到对象并将这些对象插入 NSMutableArray 时遇到问题。

表格 View .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);
}

当我尝试检查 viewDidLoad 中的 self.movi​​eList 时,它有零个对象,但是当我检查 中的 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"
  }
]

最佳答案

AFJSONRequestOperation 正在异步加载数据。因此,当 [错误命名 -- 应该只是 loadDataFromAPI] getDataFromAPI 方法返回时,数据尚未真正加载。

您的 createMovies: 方法应触发 UI 刷新,从而显示电影。

关于ios - 将对象存储到 NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14306706/

相关文章:

iphone - 当我们从表中重新加载数据时,UITable View 数据源和委托(delegate)的顺序是什么?

objective-c - 更改 NSMutableArray 中所有对象的属性

ios - NSDateFormatter 中的 AM/PM 问题

ios - 测试 Xcode 项目时无法访问 AppDelegate

ios - iOS下使用Stitcher时OpenCV编译报错

ios - 遍历对象数组并添加到数组数组

ios - 在 NSUserDefault 中保存 NSMutableArray 给出 nil

c++ - 错误:__cxxabiv1::__si_class_type_info 的 libc++abi.dylib`vtable

objective-c - 如何在运行时识别方法的返回类型?

ios - UIPopoverController 以不同的速度调整 popover 和 content-viewcontroller(uinavigationcontroller) 的大小