我在数组中有自定义对象(Scan)。我想删除一个特定的对象,它不起作用。这是我的代码:
class Scan : NSObject, NSCoding {
let code : String
let title : String
let scanDate : NSDate
init(code: String, title: String, scanDate: NSDate) {
self.code = code
self.title = title
self.scanDate = scanDate
}
// MARK: NSCoding
required convenience init?(coder decoder: NSCoder) {
guard let code = decoder.decodeObjectForKey("code") as? String,
let title = decoder.decodeObjectForKey("title") as? String,
let scanDate = decoder.decodeObjectForKey("scanDate") as? NSDate
else { return nil }
self.init(code: code, title: title, scanDate: scanDate)
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.title, forKey: "title")
coder.encodeObject(self.code, forKey: "code")
coder.encodeObject(self.scanDate, forKey: "scanDate")
}
}
func == (lhs: Scan, rhs: Scan) -> Bool {
return lhs.code == rhs.code
}
在另一堂课中:
func saveScan(scan: Scan){
var allScans = scans()
allScans.append(scan)
NSKeyedArchiver.archiveRootObject(allScans, toFile: filePath)
}
func deleteScan(scan: Scan) {
var archivedScans = scans()
archivedScans.removeObject(scan)
NSKeyedArchiver.archiveRootObject(archivedScans, toFile: filePath)
}
func scans() -> [Scan] {
let scans = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? [Scan] ?? [Scan]()
return scans
}
数组扩展名:
extension Array where Element : Equatable {
mutating func removeObject(object : Generator.Element) {
if let index = self.indexOf(object) {
self.removeAtIndex(index)
}
}
}
archivedScans.removeObject(scan)
无法正常工作(archivedScans在removeObject之前和之后具有相同的元素)。
你知道为什么删除不起作用吗?
答案 0 :(得分:0)
由于Scan
类是NSObject
的子类,因此未正确实现相等性。我们应该覆盖isEqual
和hash
方法
正确的代码:
import Foundation
class Scan : NSObject, NSCoding {
let code : String
let title : String
let scanDate : NSDate
init(code: String, title: String, scanDate: NSDate) {
self.code = code
self.title = title
self.scanDate = scanDate
}
// MARK: NSCoding
required convenience init?(coder decoder: NSCoder) {
guard let code = decoder.decodeObjectForKey("code") as? String,
let title = decoder.decodeObjectForKey("title") as? String,
let scanDate = decoder.decodeObjectForKey("scanDate") as? NSDate
else { return nil }
self.init(code: code, title: title, scanDate: scanDate)
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.title, forKey: "title")
coder.encodeObject(self.code, forKey: "code")
coder.encodeObject(self.scanDate, forKey: "scanDate")
}
override func isEqual(object: AnyObject?) -> Bool {
if let object = object as? Scan {
return self.code == object.code
}
return false
}
override var hash: Int {
return self.code.hashValue
}
}