Jul*_*les 3 xcode cocoa-touch objective-c analyzer
升级后,我收到了分析仪警告......
Returning 'self' while it is not set to the result of '[(super or self) init...]'
不知道它有什么不对吗?
- (id)initWithFrame:(CGRect)frame {
if (self == [super initWithFrame:frame]) {
[self initLayers];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
ugh*_*fhw 13
摆脱第二个等号.适当的if陈述是:
if(self = [super initWithFrame:frame])
Run Code Online (Sandbox Code Playgroud)
这一点是超级实现可以返回一个不同但仍然有效的对象,而不是self的当前值.在这种情况下,if语句将为false,因为对象不同,因此不会进行初始化.但是,由于它返回了一个不同的对象,超级实现应该释放旧的self,这就是你要返回的内容.这意味着您可能返回了无效指针.
通过仅使用一个等号,您可以设置变量而不是比较变量.因为if(object)如果是真的object不是nil,它是等价于:
if((self = [super initWithFrame:frame]) != nil)
Run Code Online (Sandbox Code Playgroud)
或者,更容易理解的版本:
self = [super initWithFrame:frame];
if(self != nil)
Run Code Online (Sandbox Code Playgroud)
此代码重新分配self为超级初始化程序返回的值,而不是仅假设返回的值相同.这就是为什么将变量设置为init...方法的结果而不是重要的原因alloc.
// good
id object = [[MyClass alloc] init];
// bad
id object = [MyClass alloc];
[object init];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4314 次 |
| 最近记录: |