Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I check for nil in copyWithZone:?

In the Sketch example, in -[<NSCopying> copyWithZone:] is not checked if -[<NSObject> init] returns nil:

- (id)copyWithZone:(NSZone *)zone {
    SKTGraphic *copy = [[[self class] alloc] init];
    copy->_bounds = _bounds;
    copy->_isDrawingFill = _isDrawingFill;
    copy->_fillColor = [_fillColor copy];
    copy->_isDrawingStroke = _isDrawingStroke;
    copy->_strokeColor = [_strokeColor copy];
    copy->_strokeWidth = _strokeWidth;
    return copy;
}

This means that there will be a null dereference at runtime if it does return nil (i.e. a bug).

Is it usual that in -[<NSCopying> copyWithZone:] the program does not check if -[<NSObject> init] returns nil? Should I also do this not? I though of this:

- (id)copyWithZone:(NSZone *)zone {
    SKTGraphic *copy = [[[self class] alloc] init];
    if (copy) {
        copy->_bounds = _bounds;
        copy->_isDrawingFill = _isDrawingFill;
        copy->_fillColor = [_fillColor copy];
        copy->_isDrawingStroke = _isDrawingStroke;
        copy->_strokeColor = [_strokeColor copy];
        copy->_strokeWidth = _strokeWidth;
    }
    return copy;
}

1 Answers

I would have to agree and say it should be checking for nil since the copy is accessing instant variables directly which will result in a crash if the copy is nil. If it were just accessing properties and methods that would not be an issue.

like image 94
Joe Avatar answered Dec 23 '25 23:12

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!