2

从 Parse Data Browser 检索对象时,我无法获取对象属性。这发生在我从“@NSManaged var friends”更改为“dynamic var friends”之后。甚至“名称”在 User.logInWithUsernameInBackground 块中也显示 nil,这很疯狂,因为登录成功。用户的 ACL 设置为“公共读取”。

用户对象:

class User : PFUser, PFSubclassing {

    dynamic var friends:[User]!
    dynamic var name:String!

     override class func load() {
        self.registerSubclass()
    }
}

与朋友一起检索用户。println 显示为零

var query = User.query()
query.includeKey("friends")
query.getObjectInBackgroundWithId(currentUser.objectId) {
    (pfObject: PFObject!, error: NSError!) -> Void in
    if pfObject != nil {
        var user = pfObject as User
        var friends = user.friends as [User]
        println("friends: \(friends)") //nil
   } else {
        println(error)
   }
}

登录。println 显示为零

User.logInWithUsernameInBackground(USERNAME, password:PASSWORD) {
        (user: PFUser!, error: NSError!) -> Void in
        if user != nil {
            println("Logged in with user: \(user.name)") //nil
        } else {
            println(error)
        }
    }
4

2 回答 2

6

对你来说更深入一点,似乎障碍是对dynamicSwift 中修饰符的作用的误解。显然,dynamic在 Swift 中用于键值观察,而不是声明要在运行时定义的变量访问器(@dynamic 在 Objective-C 中所做的)

dynamic有关Swift https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-XID_8中的描述,请参阅此内容

这用于描述为什么@NSManaged 以@dynamic 在Objective-C 中的工作方式 https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html#/ /apple_ref/doc/uid/TP40014216-CH5-XID_66

于 2014-09-08T14:09:51.203 回答
0

使用 xCode 6.1.1,我可以在没有桥接头的情况下完成这项工作,但我确实需要使用 @NSManaged。这是如何...只是:

import Parse 

在调用模块的顶部。对于类声明 .swift 文件动态不起作用,因此我需要对变量类型使用 @NSManaged 以使它们成功链接到 Parse 类变量。像这样:

class PSCategory : PFObject, PFSubclassing {
    override class func load() {
        self.registerSubclass()
    }
    class func parseClassName() -> String! {
        return "Category"
    }

    @NSManaged var Name: String
}

然后在我的查询中,所有名称都是动态链接的:

var query = PSCategory.query() // PFQuery(className: "Category")

query.cachePolicy = kPFCachePolicyCacheElseNetwork // kPFCachePolicyNetworkElseCache
query.maxCacheAge = 60 * 60 * 24  // One day, in seconds.
query.findObjectsInBackgroundWithBlock {
    (categories: [AnyObject]!, error: NSError!) -> Void in
    if error == nil {
        for abstractCategory in categories {
            let category = abstractCategory as PSCategory

            NSLog("Category Name: %@", category.Name)
        }
    } else {
        NSLog("Unable to retrieve categories from local cache or network")
    }
}
于 2015-01-03T18:42:43.110 回答