Ios 对NSDictionary对象的NSArray排序的最佳方法?
我正在努力对一系列字典进行排序 我的字典有两个价值观:兴趣、价格、受欢迎程度等Ios 对NSDictionary对象的NSArray排序的最佳方法?,ios,objective-c,sorting,nsarray,nsdictionary,Ios,Objective C,Sorting,Nsarray,Nsdictionary,我正在努力对一系列字典进行排序 我的字典有两个价值观:兴趣、价格、受欢迎程度等 有什么建议吗?编写一个排序函数,比较两个词典中的相关字段。当您使用此版本时,例如可以使用NSArray#sortedArrayUsingFunction:context:对数组进行排序 请参见像这样使用NSSortDescriptor NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:
有什么建议吗?编写一个排序函数,比较两个词典中的相关字段。当您使用此版本时,例如可以使用
NSArray#sortedArrayUsingFunction:context:
对数组进行排序
请参见像这样使用
NSSortDescriptor
NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES];
stories = [stories sortedArrayUsingDescriptors:@[descriptor]];
recent = [stories copy];
stories
是要排序的数组recent
是另一个具有已排序字典值的可变数组。使用您必须排序的键值更改@“兴趣”
祝你一切顺利
[array sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];
我真的不想把它分成多行。这对我来说已经足够简单了。更新,SortusingDescriptor现在可以使用Descriptor进行排序 因此,它就像:
items = [items sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
您可以从父属性遍历到所需的子属性。例如
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"parent.child.child" ascending:YES];
记住分配给数组这很好,但它确实会泄漏。1) 排序描述符应被释放或自动删除,2)不需要复制调用,可以删除该行。NSSortDescriptor*描述符=[[NSSortDescriptor alloc]initWithKey:@“兴趣”升序:是]自动删除];[stories SortusingDescriptor:[NSArray arrayWithObjects:descriptor,nil];您可以使用NSSortDescriptor*描述符=[NSSortDescriptor sortdescriptor with key:@“interest”升序:YES];最近=[[stories sortedArrayUsingDescriptors:[NSArrayWithObjects:descriptor,nil]]copy];您需要在排序调用期间存储输出:NSArray*recent=[stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];NSSortDescriptor*描述符=[NSSortDescriptor SortDescriptor WithKey:@“name”升序:YES];[结果ray1排序描述符:[NSArray arrayWithObjects:描述符,无];您似乎混淆了-
[NSArray SortudArray Using Descriptors]
和-[NSMutableArray sortUsingDescriptors]
。最新的仍然存在,没有被取代。你这个小明星。这帮我整理了一本小词典。谢谢!它没有回答这个问题!
array = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];