Nektarios Nektarios - 1 year ago 238
Objective-C Question

Copy NSView in cocoa / objective-c

I can't see any way to copy an NSView and create an identical NSView object. I see google hits about "use an NSData" but I don't understand that.

Answer Source

To straight up "copy" an NSView, the view has to implement the NSCopying protocol. Unfortunately, NSView does not.

Fortunately, it does implement the NSCoding protocol, which means we can still duplicate a view like:

NSData * archivedView = [NSKeyedArchiver archivedDataWithRootObject:myView];
NSView * myViewCopy = [NSKeyedUnarchiver unarchiveObjectWithData:archivedView];

And voilá! You now have a duplicate of myView.

Edit: (Swift version)

let archivedView = NSKeyedArchiver.archivedData(withRootObject: myView)
let myViewCopy = NSKeyedUnarchiver.unarchiveObject(with: archivedView)

(archivedView is of type Data, not NSData)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download