I wanna implement the function that drag a tableview cell on a "Delete Icon" to delete it.
Now my question is how can I cast my Type to NSItemProviderWriting/NSItemProviderReading to use drag and drop.
I'm following this tutorial: https://exploringswift.com/blog/creating-a-nsitemprovider-for-custom-model-class-drag-drop-api . While I failed and I still could not understand how it works.
It says that Type 'Task' does not conform to protocol 'Decodable'.('Task' is my custom model) and I also don't know what 'kUTTypeData' is in this tutorial...
Can anyone help to how to implement these protocol?
import Foundation
import CoreData
@objc(Task)
public class Task: NSManagedObject, NSItemProviderWriting, NSItemProviderReading, Codable {
public override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
<#code#>
}
required public init(from decoder:Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
}
public static var writableTypeIdentifiersForItemProvider: [String] {
return []
}
public func loadData(withTypeIdentifier typeIdentifier: String, forItemProviderCompletionHandler completionHandler: @escaping (Data?, Error?) -> Void) -> Progress? {
let progress = Progress(totalUnitCount: 100)
do {
let encoder = JSONEncoder()
let data = try encoder.encode(self)
progress.completedUnitCount = 100
completionHandler(data, nil)
} catch {
completionHandler(nil, error)
}
return progress
}
public static var readableTypeIdentifiersForItemProvider: [String] {
return []
}
public static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> Self {
let decoder = JSONDecoder()
do {
let myJSON = try decoder.decode(Task.self, from: data)
return myJSON as! Self
} catch {
fatalError("Err")
}
}
}
Instead of making the NSManagedObject
conform to the protocols, have you considered using .objectID.uriRepresentation()
in the drag/drop handlers?
Here you can find an explanation for implementing Codable
with Core Data entities: https://stackoverflow.com/a/46917019
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.