gpt4 book ai didi

ios - 如果我使用比较对对象进行排序,如果其中一个对象为零,我该如何告诉它不进行排序?

转载 作者:行者123 更新时间:2023-11-28 20:14:29 25 4
gpt4 key购买 nike

假设我有以下代码块:

[allKeys sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary *firstArticle = [articles objectForKey:(NSString *)obj1];
NSNumber *firstSortID = [firstArticle objectForKey:@"sort_id"];

NSDictionary *secondArticle = [articles objectForKey:(NSString *)obj2];
NSNumber *secondSortID = [secondArticle objectForKey:@"sort_id"];

if (firstSortID == nil || secondSortID == nil) {
return nil;
}
else {
return [secondSortID compare:firstSortID];
}
}];

我收到警告:

Incompatible pointer to integer conversion returning 'void *' from a function with result type 'NSComparisonResult' (aka 'enum NSComparisonResult')

但基本上,如果其中之一为 nil,它就会崩溃,因为比较没有意义。我如何告诉它如果它为零,不要打扰,就停下来。

最佳答案

您必须决定如何对 nil 值进行排序。他们很可能应该放在列表的末尾。你想要这样的东西:

if (firstSortID) {
if (secondSortID) {
// Both set, compare
NSComparisonResult result = [firstSortID compare:secondSortID];
if (result == NSOrderedSame) {
// optionally do another comparison on a secondary value
// result = ...
}
return result;
} else {
// Have 1st but not 2nd
return NSOrderedAscending;
}
} else {
if (secondSortID) {
// Have 2nd but not 1st
return NSOrderedDescending;
} else {
// Both nil, treat as the same
// Another option here is to look at another value in the dictionary to be used as a secondary sort
return NSOrderedSame;
}
}

关于ios - 如果我使用比较对对象进行排序,如果其中一个对象为零,我该如何告诉它不进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18562824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com