您应该为进行比较的 VerticePoint 对象实现方法,如下所示:
- (NSComparisonResult)compare:(VerticePoint *)vpoint
{
if (self.x > vpiont.x)
return NSOrderedAscending;
else if (self.x < vpiont.x)
return NSOrderedDescending;
else if (self.y > vpiont.y)
return NSOrderedAscending;
else if (self.y < vpiont.y)
return NSOrderedDescending;
else
return NSOrderedSame;
}
之后,如果您的数组带有 VerticePoint 对象,则调用:
NSArray *sortedArray = [yourArray sortedArrayUsingSelector:@selector(compare:)];
希望这有帮助。
//扩展
如果您不想创建 NSManagedObject 的子类,可以使用 NSSortDescriptor:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"ENTITYNAME" inManagedObjectContext:context]];
NSSortDescriptor *sortDescriptorX = [NSSortDescriptor sortDescriptorWithKey:@"yourObjecy.x" ascending:YES];
NSSortDescriptor *sortDescriptorY = [NSSortDescriptor sortDescriptorWithKey:@"yourObjecy.y" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptorX, sortDescriptorY, nil]];
NSArray *sortedResults = [context executeFetchRequest:request error:nil];
// 扩展
或者最简单的解决方案是
NSArray *returnedVertices = [verticesPassed sortedArrayUsingComparator:^(id obj1, id obj2) {
//Cast to your object:
VerticePoint *p1 = (VerticePoint*)obj1;
VerticePoint *p2 = (VerticePoint*)obj2;
if (p1.x > p2.x)
return NSOrderedAscending;
else if (p1.x < p2.x)
return NSOrderedDescending;
else if (p1.y > p2.y)
return NSOrderedAscending;
else if (p1.y < p2.y)
return NSOrderedDescending;
else
return NSOrderedSame;
}
];