objective-c - '==' 的左操作数是垃圾值

标签 objective-c ios operands

我在分析我的 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/

相关文章:

ios - iCloud 用于保存相当频繁的游戏状态更改

c# - CS0019 运算符不能应用于类型为 'bool' 和 'int' 的操作数

python - 方法上不支持的操作数类型

iphone - 配置自动布局后出现大量错误

ios - 为什么我取消选中设备方向后 iPhone 仍然旋转(从 info.plist 文件中删除旋转)

objective-c - 与 ValueTransformer 绑定(bind)时 NSColorWell 无法打开

ios - 如何在 UIScrollView 中使用 UIGestureRecognizer

java - 操作数类型错误

objective-c - 我应该怎么做才能调用audioPlayerDidFinishPlaying :

ios - 如何从 UITextField 获取 UITableViewCell 的索引?