Hello,
Deciding to move on with the next projects from HWS, I hit a wall trying to do one of the tasks from Project 33. Here it is:
"We made the Whistle
class inherit from NSObject
. Can you make it conform to the NSCoding
protocol? You might find project 12’s guide to NSCoding
and UserDefaults
in Swift useful.
"
To those that haven't done this project, it's all about CloudKit. The Whistle
class is uploaded and fetched from the iCloud. If I get this right, NSCoding here is useful because once we download a whistle, we can save it to UserDefaults and it stays on the list if our device happens to be offline. Correct?
Anyway, here is what I did with the Whistle
class:
class Whistle: NSObject, NSCoding {
var recordID: CKRecord.ID!
var genre: String!
var comments: String!
var audio: URL!
init (recordID: CKRecord.ID, genre: String, comments: String, audio: URL) {
self.recordID = recordID
self.genre = genre
self.comments = comments
self.audio = audio
}
// Reading the thing from disk:
required init?(coder aDecoder: NSCoder) {
recordID = aDecoder.decodeObject(forKey: "recordID") as? CKRecord.ID ?? nil
genre = aDecoder.decodeObject(forKey: "genre") as? String ?? ""
comments = aDecoder.decodeObject(forKey: "comments") as? String ?? ""
audio = aDecoder.decodeObject(forKey: "audio") as? URL ?? nil
}
// Writing the thing to disk:
func encode(with aCoder: NSCoder) {
aCoder.encode(recordID, forKey: "recordID")
aCoder.encode(genre, forKey: "genre")
aCoder.encode(comments, forKey: "comments")
aCoder.encode(audio, forKey: "audio")
}
}
And I guess that all would be good if it weren't for this code in the main table view controller:
operation.recordFetchedBlock = { record in
let whistle = Whistle() // Here I get an error saying: "Missing argument for parameter 'coder' in call"
whistle.recordID = record.recordID
whistle.genre = record["genre"]
whistle.comments = record["comments"]
newWhistles.append(whistle)
}
I know that I should put let whistle = Whistle(coder: someCoder)
but I have no clue what 'someCoder' should be here. I've read about initializing aDecoders, superinits etc. but none of the StackOverflow tips or tutorials have worked so far. Or maybe there is some simple solution I have overlooked? As always, I will be very grateful for any help. Cheers!