SWIFT how to store a CLASS containing a STRUCT with an ARRAY of STRUCT inside USERDEFAULTS

时间:2015-07-28 22:38:24

标签: arrays nsmutablearray nsuserdefaults swift2 nscoding

the problem may sound weird but is exactly my situation. I have a class containing a struct with only an array inside: an array of another struct. I would like to store an object of the class into user default. Let see some code

struct Inside {
    var something: String
    var somethingElse: Int
}

struct Outside {
    var array = [Inside]()
}

class TheClass:  {
    var array = [Outside]()
}

var a = TheClass()

//now I would like to put 'a' into UserDefaults

I tried to use NSCoding, like you can see in this code (the code compiles)

class TheClass: NSObject, NSCoding {
    var array: NSMutableArray = NSMutableArray()
    override init(){
        self.elementi = []
    }

    required init(coder aDecoder: NSCoder) {
        elementi = aDecoder.decodeObjectForKey("elementi") as! NSMutableArray
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(elementi, forKey: "elementi")
    }
}

but when I try to add an object of struct Outside into the NSMutableArray, I get an error. I found out that one solution is to convert into an NSValue. Here is the code in objective C, I am not able to translate it in swift

//here 'a' denotes an object of Outside struct that we want to insert into the NSMutableArray stored inside an object of TheClass (we cannot add it directly to the NSMutableArray)
NSValue* value = [NSValue value:&a withObjCType:@encode(Outside)];         

//To extract it later:
    [value getValue:&value];

I don't know how to solve this problem. Maybe I can change the struct to classes, in this way NSObject is no more need and I can use NSCoding directly (can be used with class object but not with struct object). But if I do this way I will get exactly the error that this guy have: SWIFT: Copying objects from arrays then changing properties and adding them back to original array

What do you suggest?

0 个答案:

没有答案