我在分析我的 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 if
和 else
:
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/