问题
I created two functions called save array and retrieve array and their job is to save and retrieve an array from the phone. My problem is that they are not working. These are the two functions.
func SaveArray (array: [IOU],fileID: String){
NSKeyedArchiver.archiveRootObject(array, toFile: fileID)
}
func RetrieveArray (fileID: String, var array: [IOU]) -> [IOU]{
if let arraytoRetrieve = NSKeyedUnarchiver.unarchiveObjectWithFile(fileID) as? [IOU]{
array = arraytoRetrieve
}
return array
}
IOU is a class I have defined like this:
class IOU : NSObject, NSCoding {
var Amount : Double
var Payer : String
var Description : String
init (amount: Double, payer: String, description: String){
self.Amount = amount
self.Payer = payer
self.Description = description
super.init()
}
required convenience init(coder decoder: NSCoder){
let amount = decoder.decodeDoubleForKey("amount")
let payer = decoder.decodeObjectForKey("payer") as! String
let description = decoder.decodeObjectForKey("description") as! String
self.init(amount: amount,payer: payer,description: description)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeDouble(self.Amount, forKey: "amount")
aCoder.encodeObject(self.Payer, forKey: "payer")
aCoder.encodeObject(self.Description, forKey: "description")
}
}
And I implemented my retrieve function in the viewWillAppear method like this:
Debts = RetrieveArray("Debts", array: Debts)
But for some unknown reason, when I run a playground test like the one below, it works just fine:
var IOUArray : [IOU] = [IOU]()
var example = IOU(amount: 70, payer: "Jackson", description: "Because")
IOUArray.append(example)
func SaveArray (array: [IOU],fileID: String){
NSKeyedArchiver.archiveRootObject(array, toFile: fileID)
}
func RetrieveArray (fileID: String) -> [IOU]{
let IOUA = NSKeyedUnarchiver.unarchiveObjectWithFile(fileID) as! [IOU]
return IOUA
}
SaveArray(IOUArray, fileID: "IOUArray")
RetrieveArray("IOUArray")
print(RetrieveArray("IOUArray")[0].Amount)
回答1:
The value of the parameter toFile
in the method archiveRootObject
and the parameter in unarchiveObjectWithFile
must be a valid file path..
archiveRootObject
returns true
if the operation was successful, otherwise false
来源:https://stackoverflow.com/questions/34627674/retrieve-array-function-not-working