[英]NSArray from NSSet - Do I have to sort it myself?
I've got data in an NSSet, and I need to get it into an NSArray. 我在NSSet中有数据,我需要将它放入NSArray中。
Do I need to sort it myself (again, this came from Core Data) or can I get it out in a sorted order? 我是否需要自己排序(再次,这来自Core Data)或者我可以按排序顺序将其排除吗?
You can specify a sort when you retrieve data with an NSFetchRequest
by setting the sortDescriptors
property to an array of NSSortDescriptor
s. 通过将
sortDescriptors
属性设置为NSSortDescriptor
数组,可以在使用NSFetchRequest
检索数据时指定排序。 But if you already have it in an NSSet
and don't want to make another fetch request, you can use: 但是如果你已经在
NSSet
拥有它并且不想再发送一个获取请求,你可以使用:
[[theSet allObjects] sortedArrayUsingDescriptors:sortDescriptors];
It'll create an interim NSArray
when you call allObjects
and then another sorted array afterwards, so it's not 100% efficient, but the overhead should be negligible for reasonably-sized data sets (and certainly less than the cost of sorting). 当你调用
allObjects
然后调用另一个已排序的数组时,它将创建一个临时NSArray
,因此它不是100%有效,但对于合理大小的数据集(并且肯定低于排序成本),开销应该可以忽略不计。
Actually, I was wrong - NSSet has the sortedArrayUsingDescriptors:
method too. 实际上,我错了 - NSSet也有
sortedArrayUsingDescriptors:
方法。 So you can just call [theSet sortedArrayUsingDescriptors:descriptors]
and do it all in one go. 所以你可以调用
[theSet sortedArrayUsingDescriptors:descriptors]
并一次完成所有操作。
You've got to sort it yourself, but it's not very hard... 你必须自己排序,但这不是很难......
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Sprocket" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortVariable" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
self.sprocketArray = mutableFetchResults;
[sortDescriptors release];
[sortDescriptor release];
[mutableFetchResults release];
[request release];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.