(iOS Swift parse.com)-可以在PFObject子类中存储自定义对象吗? [英] (iOS Swift parse.com) - Possible to store custom object in PFObject subclass?

查看:102
本文介绍了(iOS Swift parse.com)-可以在PFObject子类中存储自定义对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift iOS中使用parse.com(1.7.3)将数据存储在本地数据存储中.在parse.com docs 此处之后,我可以将PFObject子类化存储一个简单的对象.但是,我希望在此对象的内部 组成一个自定义对象,并且在执行此操作时遇到了困难.

我已将此问题归结为最基本的问题,并在下面包含了我的代码.基本上,我存储了一个名为"Test"的PFObject子类,该子类将存储一个String(testString)和一个名为Test2的自定义对象.反过来,Test2也将存储一个String(testString).我认为Test2也需要继承PFObject.

Test - testString(String)
     - test2(Test2)
          - testString(String)

AppDelegate.swift

(在AppDelegate中注册子类而不是Initialize方法-请参见

Test2.swift

class Test2:PFObject, PFSubclassing {
    @NSManaged var testString:String

    static func parseClassName() -> String {
        return "Test2"
    }
}

Test.swift

class Test:PFObject, PFSubclassing {
    @NSManaged var testString:String
    @NSManaged var test2:Test2

    static func parseClassName() -> String {
        return "Test"
    }
}

ViewController.swift

override func viewDidLoad() {
    saveTest()  //toggle between save and load, don't do both!
    //loadTest()
}
func saveTest() {
        var test2 = Test2()
        test2.testString = "I am Test 2"

        var test = Test()
        test.testString = "I am Test"
        test.test2 = test2
        test.pinInBackground()
}
func loadTest() {
    let query = PFQuery(className:Test.parseClassName())
    query.fromLocalDatastore()
    query.findObjectsInBackgroundWithBlock({
        (objects:[AnyObject]?, error: NSError?) in
        if let error = error {
            println("THERE WAS AN ERROR")
            // There was an error
        } else {
            if let objects = objects as? [PFObject] {
                for object in objects {
                    //We have an object!
                    println("We have a PFObject, now to cast as Test")
                    if let object = object as? Test {
                        println(object)
                    }
                }
            }
        }
    })
}

因此loadTest中的println在控制台中输出以下内容:

<Test: 0x7ff2da75e810, objectId: new, localId: local_15a085d00030543f> {
    test2 = "<Test2: 0x7ff2db90fe50, objectId: new>";
    testString = "I am Test";
}

如果我尝试访问test2属性或test2属性,则该应用程序挂起.我也无法获取" Test对象.奇怪的是,如果我加载本地存储的任何Test2对象(与上面的loadTest方法相同,但提及Test被Test2替换的话),我找到该Test2对象:

<Test2: 0x7f94b1f1e850, objectId: new, localId: (null)> {
    testString = "I am Test 2";
}

因此在固定测试对象时,也固定了test2.但是由于某种原因,test2对象未连接到测试对象.<​​/p>

我开始迷路了,似乎找不到相关的(或准确的)文档或示例项目,这些文档或示例项目可能在一秒钟之内就能解决所有问题……什么是最好的方法(如果有)在PFObject子类中组成一个自定义对象?

在这种情况下,这可以为您提供帮助.您的 Test 类是 PFObject 的子类.并且在Test类中有一个自定义对象,名为 Test2 .

在您的 Test2.swift 文件中,创建一个方法,该方法将返回包含其对象所有属性的 NSDictionary 对象. 与此类似:

class func objDetail() -> NSDictionary {
return [
    "key1": self.property1,
    "key2": self.property2,
    // ...
        ] as NSDictionary
}

您可以使用此词典将对象详细信息作为对象存储在 Test 对象中.现在,解析支持字典,您已将其转换为字典.它将保存对象.

现在在您的swift文件中添加另一种方法,以基于字典值创建对象.

convenience init(_ dictionary: Dictionary<String, AnyObject>) {
    self.init()

    title = dictionary["title"] as? NSString
    shortDescription = dictionary["shortDescription"] as? NSString
    newsDescription = dictionary["newsDescription"] as? NSString
    link = dictionary["link"] as? NSURL

}

要检索对象,请在loadTest方法的query.findObjectsInBackgroundWithBlock中调用该对象的init方法,并使用从解析中获得的字典值创建对象.

希望,我的想法对您有帮助..:)

I am attempting to store data in the local data store using parse.com(1.7.3) in Swift iOS. Following the parse.com docs here, I am able to subclass PFObject to store a simple object. However I am hoping to compose a custom object inside this object and am finding difficulties in doing this.

I have stripped this problem back to its most basic and include my code below. Basically I am storing a PFObject subclass called 'Test', which will store a String(testString), and a custom object called Test2. Test2 in turn will also store a String(testString). I assume that Test2 also needs to subclass PFObject.

Test - testString(String)
     - test2(Test2)
          - testString(String)

AppDelegate.swift

(Registering subclass in AppDelegate instead of Initialise method - see here for more details.)

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    Test.registerSubclass()
    Test2.registerSubclass()

    Parse.enableLocalDatastore()
    Parse.setApplicationId("...", clientKey: "...")
}

Test2.swift

class Test2:PFObject, PFSubclassing {
    @NSManaged var testString:String

    static func parseClassName() -> String {
        return "Test2"
    }
}

Test.swift

class Test:PFObject, PFSubclassing {
    @NSManaged var testString:String
    @NSManaged var test2:Test2

    static func parseClassName() -> String {
        return "Test"
    }
}

ViewController.swift

override func viewDidLoad() {
    saveTest()  //toggle between save and load, don't do both!
    //loadTest()
}
func saveTest() {
        var test2 = Test2()
        test2.testString = "I am Test 2"

        var test = Test()
        test.testString = "I am Test"
        test.test2 = test2
        test.pinInBackground()
}
func loadTest() {
    let query = PFQuery(className:Test.parseClassName())
    query.fromLocalDatastore()
    query.findObjectsInBackgroundWithBlock({
        (objects:[AnyObject]?, error: NSError?) in
        if let error = error {
            println("THERE WAS AN ERROR")
            // There was an error
        } else {
            if let objects = objects as? [PFObject] {
                for object in objects {
                    //We have an object!
                    println("We have a PFObject, now to cast as Test")
                    if let object = object as? Test {
                        println(object)
                    }
                }
            }
        }
    })
}

So the println in loadTest outputs the following in the console:

<Test: 0x7ff2da75e810, objectId: new, localId: local_15a085d00030543f> {
    test2 = "<Test2: 0x7ff2db90fe50, objectId: new>";
    testString = "I am Test";
}

If I try to access the test2 property or a property of test2, the app hangs. I also am not able to 'fetch' the Test object. Curiously If I load any Test2 objects stored locally(identical to the loadTest method above with any mention of Test replaced with Test2), I do find the Test2 object:

<Test2: 0x7f94b1f1e850, objectId: new, localId: (null)> {
    testString = "I am Test 2";
}

So in pinning the test object, test2 is being pinned too. However the test2 object is not connecting to the test object for some reason.

I'm starting to get lost, and can't seem to find relevant(or accurate) documentation or sample projects which would probably clear all this up in a second... What is the best approach(if any) to compose a custom object inside a PFObject subclass?

解决方案

Here's an idea which can help you in this case. Your Test class is a subclass of PFObject. And you have a custom object inside Test class, named Test2.

In your Test2.swift file, create a method that would return an NSDictionary object containing all properties of its object. Somewhat similar to this :

class func objDetail() -> NSDictionary {
return [
    "key1": self.property1,
    "key2": self.property2,
    // ...
        ] as NSDictionary
}

And you could use this dictionary to store your object details as an object in your Test object. Now, parse supports dictionary and you've converted it in dictionary. It would save the object.

Now add another method in your swift file to create object based on dictionary values.

convenience init(_ dictionary: Dictionary<String, AnyObject>) {
    self.init()

    title = dictionary["title"] as? NSString
    shortDescription = dictionary["shortDescription"] as? NSString
    newsDescription = dictionary["newsDescription"] as? NSString
    link = dictionary["link"] as? NSURL

}

For retrieving object, in your loadTest method's query.findObjectsInBackgroundWithBlock call this object's init method and create object with values of dictionary you get from parse.

Hope, my idea helps you.. :)

这篇关于(iOS Swift parse.com)-可以在PFObject子类中存储自定义对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆