【问题标题】:cannot execute method insde dispatch_async()无法执行方法 insde dispatch_async()
【发布时间】:2015-03-21 17:38:43
【问题描述】:

我正面临一些我无法解决的问题。我正在下载 json 数据并使用返回的值(在 dispatch_async(get_main_queue) 内)实例化 Core Data 对象。一切都完成后,我尝试呈现另一个视图(tableView 包含这些对象),但我的 tableviewcontrollers 没有被调用。但是,如果我从该块之外的方法(在 connectionDidFinishing NSURLConnection 内部)呈现我的 viewController,一切正常。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

id jsonObject = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];


if ([jsonObject isKindOfClass:[NSArray class]]) {

    NSArray *deserializedArray = (NSArray *)jsonObject;

    if (deserializedArray.count > 0) {

        dispatch_async(dispatch_get_main_queue(), ^{
            for (NSDictionary *jsonElement in deserializedArray)
            {

                // Create a new location object and set its props to JsonElement properties
                Patient *syncPatient = [[PatientStore sharedStore] createPatient];


                syncPatient.firstName = jsonElement[@"firstname"];
                syncPatient.lastName = jsonElement[@"lastname"];      
            }

        });
        [self login]; // --> does not work.
    }

}
}

[自我登录] 不起作用。但如果我从 didFinishLoading 方法之外调用它,它就可以工作。

我认为这与 dispatch_async() 有关,但我不知道如何从外部自动调用此方法(例如使用“我已完成”通知)。

有人可以帮忙吗?

非常感谢!

更新

它在块内也不起作用。看起来 [self login] 发生在 for 循环指令之前。

if (deserializedArray.count > 0) {

    dispatch_async(dispatch_get_main_queue(), ^{
        for (NSDictionary *jsonElement in deserializedArray)
        {

            // Create a new location object and set its props to JsonElement properties
            Patient *syncPatient = [[PatientStore sharedStore] createPatient];


            syncPatient.firstName = jsonElement[@"firstname"];
            syncPatient.lastName = jsonElement[@"lastname"];      
        }
    [self login]; // --> does not work either here. As if it was executed before what is inside the for loop.
    });

}

} }

【问题讨论】:

    标签: ios core-data queue grand-central-dispatch dispatch-async


    【解决方案1】:

    [self login] 在核心数据保存开始后立即执行,因为它在块外部。如果你把它放在里面,它会在循环结束后执行

    你可以用一个简单的命令行项目来测试,这个项目在 main.swift 中:

    import Foundation
    
    dispatch_async(dispatch_get_main_queue()) {
        var j = 0
        for _ in 1...1000 { j++ }
        println("The value of j is \(j).")
    }
    dispatch_main()
    

    输出:The value of j is 1000.

    println 显然是在 循环之后执行的。

    创建对象后,不要忘记保存:

    [managedObjectContext save:nil];
    

    【讨论】:

    • 感谢您的回复,但我应该补充一点,即使方法位于块的末尾,它也会失败。看起来它是在之前发生的事情之前执行的。它似乎只在 NSConnection 方法之外工作。我不知道为什么这个 dispatch() 会出错...
    • 你是什么意思“在块的末尾”?里面还是外面?我不明白这句话的语法或含义:“看起来好像是在之前发生的事情之前执行的。”
    • 我用一个例子更新了这个问题,显示我的方法登录是在之前执行的,即使它在块内。我希望上面的更新能让事情更容易理解我的意思。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多