Search code examples
iphoneobjective-cipadnscopying

copyWithZone issue


I am trying to make a copy of my UIViewController subclass by doing:

BookViewController *bookVC = [catalogFlatViewController copy];

and I have the following error:

'-[BookViewController copyWithZone:]: unrecognized selector sent to instance 0x8e5f00'

Solution

  • UIViewController does not conform to NSCopying. If you want to make a copy, you have to use NSCoding:

    NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:controller];
    UIViewController *newController = [NSKeyedUnarchiver unarchiveObjectWithData:archive];
    

    If you've added new ivars to your view controller, you'll have to override the NSCoding methods (encodeWithCoder: and initWithCoder:) to serialize and deserialize these correctly. See Archives and Serializations Programming Guide.

    BTW, this is basically how a nib file works.