Is there a better way to avoid 'Sign comparison' warning when comparing NSIndexPath's row and NSArray count?

拟墨画扇 提交于 2019-12-10 13:13:05

问题


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')

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.


回答1:


You could implement a category that does it for you :

@implementation NSArray (SignedCount)

- (NSInteger) signedCount
{
    NSInteger count = (NSInteger)[self count];
    return count;
}

@end


来源:https://stackoverflow.com/questions/21724824/is-there-a-better-way-to-avoid-sign-comparison-warning-when-comparing-nsindexp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!