I have a custom class that conforms NSCoding protocol. Below is how I implement the protocol's methods.
User.swift
required init?(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: #keyPath(name)) as! String
self.age = aDecoder.decodeInteger(forKey: #keyPath(age))
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: #keyPath(name))
aCoder.encode(age, forKey: #keyPath(age))
}
I set the reading options to:
static func readingOptions(forType type: String, pasteboard: NSPasteboard) -> NSPasteboardReadingOptions {
return .asKeyedArchive
}
This object will be put inside a NSDragPboard
whenever the user drag a cell row on NSOutlineView
. You can see the implementation below:
UserViewController.h
var users: User // Store the users to be used in the outlineView
.
.
.
func outlineView(_ outlineView: NSOutlineView, writeItems items: [Any], to pasteboard: NSPasteboard) -> Bool {
if let user = items.first as? User {
pasteboard.clearContents()
pasteboard.writeObjects([user])
return true
}
return false
}
After the user finish the dragging by releasing the mouse button, the app will get the pasteboard content, by doing:
func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
let pasteboard = info.draggingPasteboard()
if let userInPasteboard = pasteboard.readObjects(forClasses: [User.self], options: nil)?.first as? User {
// We can access the user in pasteboard here
}
}
But the problem is, the data from the pasteboard have different memory address than the data in the outlineView.
If we try to find the user in the outlineView using the user from the pasteBoard, we can't find it.
for user in self.users {
if user == userInPasteboard {
print("We found the user that was placed on pasteboard") // Never executed
}
}
I can implement the Equatable
protocol for the User class. But I think if somehow we can make the Object that's read from the pasteboard to have the same pointer address as Object that's written to the pasteboard, it would work.
Below is what I'm trying to achieve:
Is it possible to achieve it? How?
user == userInPasteboard
? Do you want to reorder inside the same outline view? – Willeke