ios - NSMutableArray 属性在函数被激发后变为 null

标签 ios objective-c json

我正在尝试从 JSON 请求中获取一个 CLLocation 数组的值,并将它们分配给一个 NSMutable 数组的属性。
这里是相关的 Controller 代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    //using a background thread to receive the json call so that the UI doesn't stall
    dispatch_async(directionQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL:openMapURL];
        [self performSelectorOnMainThread:@selector(fetchedData:)
                               withObject:data waitUntilDone:YES];
    });

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

- (void)fetchedData:(NSData *)responseData 
{
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseData //turn the data from the json request into a gigantic dictionary
                                     options:0
                                       error:&error];

    NSDictionary* route = [json objectForKey:@"route"]; //created a dictionary out of the contents of route
    NSDictionary* shape = [route objectForKey:@"shape"]; //create a sub-dictionary with the contents of shape
    NSArray* shapePoints = [shape objectForKey:@"shapePoints"]; //turn shapePoints object into an NSArray

    //Loop to turn the array of coordinate strings into CLLocation array
    NSMutableArray* locations = [[NSMutableArray alloc] init];
    NSUInteger i;
    for (i = 0; i < ([shapePoints count])/2 ; i = i+2) 
    {
        [locations addObject: [[CLLocation alloc]
                               initWithLatitude:[[shapePoints objectAtIndex:i] floatValue]
                               longitude:[[shapePoints objectAtIndex:i+1] floatValue]
                               ]];
    }

    //When I NSLog within the function, the array has the correct data. But in viewDidLoad
    //the array is null
    [self.coordinates initWithArray:locations copyItems:YES];   
}

为什么这个数组在 viewDidLoad 中变成了 null?

最佳答案

您正在使用 GCD 发出异步请求以从 viewDidLoad 获取数据方法。由于它是异步的,它不会阻塞 viewDidLoad方法。一旦异步请求下载并被解析,数组就会被填充。这就是你的数组是 nil 的原因在 viewDidLoad .

如果在数据下载并填充数组之前您的 UI 看起来是空白的,您可以选择显示事件指示器。这将使应用程序用户知道某些事件正在进行。

希望有帮助!

关于ios - NSMutableArray 属性在函数被激发后变为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18651247/

相关文章:

ios - 无法解析 'Class is not key value coding-compliant'

ios - DISPATCH_QUEUE_CONCURRENT和全局并发调度队列之间有什么区别

ios - 将 View 推送到选项卡 Controller 中的 View Controller

ios - NSManagedObject 类关系中的 NSPredicate 键

ios - Objective C 中方法名称的命名约定

javascript - 从外部文件在 postman 中加载 json 模式

java - 在 Java 中解析 JSON

ios - 修复 Xcode 警告的快速方法

ios - 与iOS应用程序集成的Facebook登录页面间歇性关闭

json - 如何避免 Couchbase 查询中的自动强制转换?