Facebook Interview Question: How would you copy a custom o... | Glassdoor

Interview Question

IOS Engineer Interview Chicago, IL

How would you copy a custom object like a "Node" from a

  search tree in Objective C?

Interview Answer

3 Answers


This question tests your depth in the use of NSObject. You cannot call copy on an NSObject directly, so your object must implement the NSCopying protocol if you would like a copy. In order to conform to the NSCopying protocol, your object must respond to the selector "copyWithZone:". In that method you must copy any NSObject instance variables, as well as primitive data types from your object.

@interface Node : NSObject

- (id)copyWithZone:(NSZone *)zone
    id copy = [[[self class] alloc] init];

    if (copy) {
        [copy setRootNode:[[self.rootNode copyWithZone:zone]];
        [copy setLeftNode:[[self.leftNode copyWithZone:zone]];
        [copy setRightNode:[[self.rightNode copyWithZone:zone]];

    return copy;

Now you can do something like:
Node *newNode = [myNode copyWithZone:zone];


Interview Candidate on Sep 14, 2014

I'd discuss tradeoffs of deep copying (suggested by interview candidate above) versus a regular copy:

- (id)copyWithZone:(NSZone *)zone {
    Node *copy = [[[self class] allocWithZone:zone] init];
    if (!copy) {
        return nil;
    copy.parent = self.parent;
    copy.left = self.left;
    copy.right = self.right;
    return copy;

This approach is more flexible if I want to create a second instance pointing to the same nodes. Additionally, all pointers can be copied on demand.

A proper solution, covering existence of both mutable and immutable counterparts, is here: https://gist.github.com/zats/c075815e1fa24b001fb2

Sash on Dec 20, 2014

One or more comments have been removed.
Please see our Community Guidelines or Terms of Service for more information.

Add Answers or Comments

To comment on this, Sign In or Sign Up.