3

在 Sketch 示例中,如果返回,-[<NSCopying> copyWithZone:]则不检查in :-[<NSObject> init]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;
}

这意味着如果它确实返回nil(即错误),则在运行时将有一个空取消引用。

通常在-[<NSCopying> copyWithZone:]程序中不检查是否-[<NSObject> init]返回nil?我也不应该这样做吗?我虽然这样:

- (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;
}
4

1 回答 1

2

我不得不同意并说它应该检查 nil,因为副本直接访问即时变量,如果副本为 nil,这将导致崩溃。如果它只是访问属性和方法,那将不是问题。

于 2011-07-15T12:55:41.483 回答