When the array is sorting, [arr sortUsingComparator:sortByTime] and then I wanna cancel the operation. What should I do?
I don't think this is easily possible. Presumably you are working in a concurrent environment. Then something like this should cause the sort to exit quickly. You need to sync access to the sortCancel
BOOL when you set it as well, just as when you get it as below.
__block BOOL sortCancel = NO;
NSObject * lock = NSObject.new; // Sync access to sortCancel
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
@synchronized ( lock ) {
// Check for cancel
if ( sortCancel ) {
// Sort has been cancelled
return (NSComparisonResult)NSOrderedSame;
}
}
// 'Normal' compare, e.g.
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
I did not test this, but this should either break the sort or cause it to complete quickly.
I wonder why you want to abort the sorting?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.