Kobe Kobe - 3 months ago 16
Swift Question

How to duplicate an array of UIViewController's

I have on array of UIViewController's which I want to duplicate it.

var data: Array<UIViewController> = []


And this is my code:

data = viewControllers.map{($0.copy() as! UIViewController)}


But this code throws exception and I can't really tell what the issue is.

Can anyone point what the problem could be ?

Answer

UIViewController does not conform to NSCopying protocol, that means it couldn't be copied. You may try to use NSKeyedArchiver \ NSKeyedUnarchiver to archive a view controller to NSData object and then unarchive it back. But it won't create the exact copy, the properties like view or childViewControllers will be most likely lost.

Copying UI elements is actually a bad approach. The correct solution would be to instantiate the view controllers one more time and set up required properties manually.