在Sketch示例中,如果-[<NSCopying> copyWithZone:]
返回-[<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;
}
答案 0 :(得分:2)
我必须同意并说它应该检查nil,因为副本直接访问即时变量,如果副本为nil将导致崩溃。如果它只是访问不会成为问题的属性和方法。