我对ios项目进行分析时出现此错误

The left operand of '==' is a garbage value

这就是代码的样子。.此方法用于对从数据库返回给我的数组进行排序。
- (NSMutableArray *)startSortingTheArray:(NSMutableArray *)unsortedArray
{
    [unsortedArray sortUsingComparator:^ NSComparisonResult(SearchResultItem *d1, SearchResultItem *d2) {
        //initalize comparison
        NSComparisonResult result;

        NSInteger manufacturerID1 = d1.manufacturerID;
        NSInteger manufacturerID2 = d2.manufacturerID;
            if (manufacturerID1 > manufacturerID2)
                return NSOrderedAscending;
            if (manufacturerID1 < manufacturerID2)
                return NSOrderedDescending;
            if (manufacturerID1 == manufacturerID2) {

            NSString *model1 = d1.model;
            NSString *model2 = d2.model;
            result = [model1 localizedCompare:model2];
        }
        if (result == NSOrderedSame) {
//..

最佳答案

编译器抱怨是因为它认为可以在==具有值之前达到result比较。

给定代码的最佳选择是使用else ifelse:

if (manufacturerID1 > manufacturerID2)
    return NSOrderedAscending; // we won't reach the comparison so result doesn't matter
else if (manufacturerID1 < manufacturerID2)
    return NSOrderedDescending; // we won't reach the comparison so result doesn't matter
else {
    NSString *model1 = d1.model;
    NSString *model2 = d2.model;
    result = [model1 localizedCompare:model2]; // in any other case, result will be set.
}
...

或者您可以这样做:
NSComparisonResult result;
...
if (manufacturerID1 > manufacturerID2)
    return NSOrderedAscending;
else if (manufacturerID1 < manufacturerID2)
    return NSOrderedDescending;

NSString *model1 = d1.model;
NSString *model2 = d2.model;
result = [model1 localizedCompare:model2];
...

甚至这样:
if (manufacturerID1 > manufacturerID2)
    return NSOrderedAscending;
else if (manufacturerID1 < manufacturerID2)
    return NSOrderedDescending;

NSComparisonResult result = [d1.model localizedCompare:d2.model];
...

通过这种方式,编译器知道如果达到比较,就已经设置了result的值。

关于objective-c - '=='的左操作数是垃圾值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12848145/

10-09 15:53
查看更多