如何从parse中的对象抓取ObjectId并在swift中将其显示为字符串

时间:2016-01-25 06:51:49

标签: ios swift object parse-platform

为什么我无法在swift中将一个Object中的“ObjectId”作为String呈现,即使它自然已经是一个字符串了?以下是我试图使用的逻辑:

//MARK: Fetch ObjectId Strings From Parse
    func fetchObjectIdString() {

        let query = PFQuery(className: "Books")
        query.whereKey("genreName", equalTo: self.genreName)
        query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

            if error == nil {

                if let objects = objects as [PFObject]! {

                    for oneObj in objects {

                        let ObjectIdFromParse = oneObj["objectId"] as! String
                        let SingleObjectId = SixthBook()
                        SingleObjectId.objectIdString = ObjectIdFromParse
                        self.arrayOfObjectId.append(SingleObjectId)
                    }
                }
            } else {

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

除了ObjectId之外,我的解析对象的所有其他字符串列都可以正常工作。它每次都会抛出异常错误。这是为什么?

3 个答案:

答案 0 :(得分:1)

使用oneObj.objectId代替您在上述代码中尝试的内容。

将第let ObjectIdFromParse = oneObj["objectId"] as! String行更改为

let ObjectIdFromParse = oneObj.objectId as! String

答案 1 :(得分:1)

来自Parse documentation on PFObjects

objectIdcreatedAtupdatedAt作为每个PFObject的属性提供,因此您不会使用[""]下标它们,而是通过{{对象上有1}},.objectId.createdAt

您也不需要强制转发为String,因为objectId始终是String(如您所述)。但是,您确实需要打开可选项(表示您知道此objectId存在)。因此,正确的代码行应该是:

.updatedAt

答案 2 :(得分:0)

这个问题到现在已经有4年了,但是也许这个答案也可以帮助其他人。

如果要存储.objectID的代表公用,则应使用引用该.objectID的对象的“ uriRepresentation”(URL)。

来自documentation

func managedObjectID(forURIRepresentation: URL) -> NSManagedObjectID?

例如,您有: 迅速4

do
{
  let entity = try self.context.fetch(fetchRequest())
  let entityObj = entity.last as! Any
  let uriID = entityObj.objectID.uriRepresentation().absoluteString
}
catch
{ 
  print("Error...") 
}

在获取ID之前,请记住保存saveContext(),否则将获得一个临时ID。

https://developer.apple.com/documentation/coredata/nsmanagedobjectid/1391691-temporaryid

您可以找到更多信息:https://developer.apple.com/documentation/coredata/nspersistentstorecoordinator/1468882-managedobjectid

希望有帮助。