Xcode 警告“未使用属性访问结果 - getter 不应用于产生副作用”
当我调用本地例程时,我收到此警告。
我的代码是这样的:
-(void)nextLetter {
// NSLog(@"%s", __FUNCTION__);
currentLetter ++;
if(currentLetter > (letters.count - 1))
{
currentLetter = 0;
}
self.fetchLetter;
}
我收到有关 self.fetchLetter 语句的警告。
该例程如下所示:
- (void)fetchLetter {
// NSLog(@"%s", __FUNCTION__);
NSString *wantedLetter = [[letters objectAtIndex: currentLetter] objectForKey: @"langLetter"];
NSString *wantedUpperCase = [[letters objectAtIndex: currentLetter] objectForKey: @"upperCase"];
.....
}
我更喜欢修复警告消息,有更好的方法来编写它吗?
谢谢!
I'm getting this warning when I'm calling a local routine.
My code is this:
-(void)nextLetter {
// NSLog(@"%s", __FUNCTION__);
currentLetter ++;
if(currentLetter > (letters.count - 1))
{
currentLetter = 0;
}
self.fetchLetter;
}
I'm getting the warning on the self.fetchLetter statement.
That routine looks like this:
- (void)fetchLetter {
// NSLog(@"%s", __FUNCTION__);
NSString *wantedLetter = [[letters objectAtIndex: currentLetter] objectForKey: @"langLetter"];
NSString *wantedUpperCase = [[letters objectAtIndex: currentLetter] objectForKey: @"upperCase"];
.....
}
I prefer to fix warning messages, is there a better way to write this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
点符号(即
self.fetchLetter
)适用于属性,而不适用于任意方法。 self.fetchLetter 被解释为“获取 'self' 的 'fetchLetter' 属性”,这不是您想要的。只需使用
[self fetchLetter]
即可。The dot notation (i.e.
self.fetchLetter
) is meant for properties, not for arbitrary methods. Theself.fetchLetter
is being interpreted as "get the 'fetchLetter' property of 'self'," which isn't what you intend.Just use
[self fetchLetter]
instead.在较新的 Xcode 版本中,即使
[object method];
也可能会触发警告。但有时我们实际上确实需要调用属性并丢弃结果,例如在处理视图控制器时,我们需要确保视图实际上已加载。所以我们正在做:
这现在也会触发“属性访问结果未使用 - getter 不应用于副作用”警告。解决方案是通过将结果类型强制转换为 void 来让编译器知道这是有意完成的:
In newer Xcode versions, even the
[object method];
may trigger the warning. But sometimes we actually do need to call a property and discard the result, for example when dealing with view controllers and we need to make sure the view is actually loaded.So we were doing:
This now also triggers the “Property access results unused - getters should not be used for side effects” warning. The solution is to let the compiler know it's done intentionally by casting the result type to void:
您使用这样的语法声明 fetchLetter 吗?
这对于你正在做的事情来说看起来是错误的。属性旨在成为变量访问器(对于 getter 而言)没有任何副作用。
您应该将 fetchLetter 声明为方法,如下所示:
并使用以下方式访问它:
You're declaring fetchLetter using syntax like this?
That looks wrong for what you're doing. Properties are intended to be variable accessors that (in the case of getters) don't have any side effects.
You should declare fetchLetter as a method, like so:
and access it using:
我刚刚解决了我的问题,在我的例子中是一个 CoreLocation 项目,使用了 Tom 和 Chris 的答案 -
我声明:
并实现如下:
I just got my problem resolved, in my case a CoreLocation Project, using both answers from Tom and Chris -
I declare:
And implemented like: