Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 903
Nektarios Avatar asked Jun 24 '10 05:06

Nektarios


1 Answers

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)

like image 54
Dave DeLong Avatar answered Sep 21 '22 12:09

Dave DeLong