gpt4 book ai didi

ios - 解析查询结果未附加到新数组

转载 作者:行者123 更新时间:2023-11-30 14:03:30 26 4
gpt4 key购买 nike

我正在使用 Swift,并且尝试将解析查询的结果附加到数组中,但是,该数组仅在查询的 for 循环中打印时才显示附加值。当我尝试在方法返回之前在循环外部打印数组时,我得到一个空数组。如何获取带有附加值的数组以在 for 循环之外显示?

class Task {   

func all() -> Array<String> {
var taskArray = Array<String>()
var query = PFQuery(className:"Task")
var currentUser = PFUser.currentUser() // this will now be nil
let userId = currentUser?.objectId
query.whereKey("userId", equalTo: currentUser!)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in

if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) tasks.")

// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
// println(object.objectId)
let title = object["title"]! as! String
taskArray.append(title)
println("Array: \(taskArray)")
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
println("Outside query array: \(taskArray)")


return taskArray
}
}

看起来外部查询是在查询之前被调用的,或者类似的东西。调试控制台:

enter image description here

最佳答案

正如您所说, println("Outside query array:\(taskArray)")println("Array:\(taskArray)") 之前调用,并且对此有一个简单的解释。

findObjectsInBackgroundWithBlock 是一种异步方法,这意味着它启动另一个线程并在该线程上工作。这意味着当您调用 findObjectsInBackgroundWithBlock 时,它会直接继续到 println("Outside query array:\(taskArray)")

<小时/>

现在,可以从 Parse 同步下载内容(因此它不会直接跳到 println("Outside query array:\(taskArray)")),但我不会推荐您去做这个。

相反,我建议您实现一个在下载完成时调用的闭包。类似于以下内容(PS,它是用 Swift 2 编写的):

//
// ViewController.swift
// ParseFun
//
// Created by Stefan Veis Pennerup on 21/09/15.
// Copyright (c) 2015 Kumuluzz. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

// MARK: - Lifecycle methods

override func viewDidLoad() {
super.viewDidLoad()

all { (tasks) -> Void in
print("The downloaded tasks are: \(tasks)")
}
}

// MARK: - Download methods

func all(completionHandler: ([String])->Void) {
// Creates the query
var taskArray = Array<String>()
let query = PFQuery(className:"Task")
let currentUser = PFUser.currentUser() // this will now be nil
query.whereKey("userId", equalTo: currentUser!)

// Starts the download
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in

if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) tasks.")

// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
let title = object["title"]! as! String
taskArray.append(title)
print("Array: \(taskArray)")
}
}

completionHandler(taskArray)

} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
}

关于ios - 解析查询结果未附加到新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32696099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com