当比较NSIndexPath的行和NSArray计数时,有没有更好的方法来避免“符号比较”警告? [英] Is there a better way to avoid 'Sign comparison' warning when comparing NSIndexPath's row and NSArray count?
问题描述
我为XCode中的iOS项目打开了Signed Comparision(又名-Wsign-compare)警告(令人惊讶的是,它默认关闭)。之后,出现了很多这样的警告:
I turned 'Signed Comparision' (aka -Wsign-compare) warnings for my iOS project in XCode (surprisingly, it was off by default). After that lots of warnings like this appeared:
/Users/michalciuba/projects/GlobeMobile/Classes/ACMailController.m:86:19: Comparison of integers of different signs: 'NSInteger' (aka 'long') and 'NSUInteger' (aka 'unsigned long')
它们通常是由比较 NSIndexPath
的 row
属性引起的, NSInteger
到 NSArray
的'count'方法返回的值,如下所示:
They are usually caused by comparing row
property of NSIndexPath
which is NSInteger
to the value returned by 'count' method of NSArray
, like this:
if(indexPath.row < [self.myDataArray count])
警告可以简单地通过转换固定:
The warning can be simply fixed by casting:
if(indexPath.row < (NSInteger)[self.myDataArray count])
然而,如果每个单独的地方比较。他们正在比较的几十个地方。
我想知道是否有更好,更聪明的方法来解决这个问题?我不想关闭此警告,因为它可能有助于防止像无符号整数下溢这样的问题。
However, it has to be done if every single place where such values are being compared. And they are being compared in dozens of places. I wonder if there is a better and more clever way to solve this problem? I don't want to turn off this warning, because it may help to prevent issues like unsigned integer underflow.
推荐答案
实现一个类别为你:
@implementation NSArray (SignedCount)
- (NSInteger) signedCount
{
NSInteger count = (NSInteger)[self count];
return count;
}
@end
这篇关于当比较NSIndexPath的行和NSArray计数时,有没有更好的方法来避免“符号比较”警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!