消除数组中的重复项并对结果进行排序
我有一个从 plist 中检索其信息的应用程序。 plist
是一个包含键(author、cat、content)的 Dictionaries
数组。 现在我想在表格中显示类别。 所以我需要以排序的方式所有独特的类别条目。
我已成功实施以下方式,但我很感兴趣这是否是“正确”的解决方案。
- 遍历 plist 数组并使用所有类别创建新的
NSMutableArray
字典的条目 - 将此
NSMutableArray
放入NSSet
中以获取唯一元素 - 将此
NSSet
放入NSArray
中以获取唯一 元素对其进行排序的可能性。 - 返回一个用排序后的 NSArray 启动的 NSMutableArray
我觉得不是,这是这样做的正确方法。 有什么建议可以做得更好吗?
多谢!
//InhaltefromWEb is a NSMutableArray
-(NSArray*) getCategories {
NSMutableArray* categorieTemp = [[NSMutableArray alloc] init];
unsigned count = [InhalteFromWeb count];
while (count--) {
NSString *tempString;
tempString=[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY];
NSLog(@"tempString %@", tempString );
[categorieTemp addObject:tempString];
}
NSSet *uniqueElements = [NSSet setWithArray:categorieTemp];
NSLog(@"categories from engine %@", categorieTemp);
NSArray* tempAr = [[[NSArray alloc] initWithArray:[uniqueElements allObjects]]sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
return [NSMutableArray arrayWithArray:tempAr];
}
I have an app which is retrieving its information from a plist.
The plist
is an array of Dictionaries
with the keys (author, cat, content).
Now I would like to show the categories in a table.
So I need all unique category entries in a sorted way.
I have successfully implemented following way but I am interested if this is the "right" solution.
- Go through plist array and make new
NSMutableArray
with all category
entries of the dictionary - put this
NSMutableArray
into aNSSet
to get unique Elements - put this
NSSet
into anNSArray
to have the possibility to sort it. - return a
NSMutableArray
initiated with the sortedNSArray
I feel not , that this is the right way of doing so.
Any suggestions to do it better ?
Thanks a lot!
//InhaltefromWEb is a NSMutableArray
-(NSArray*) getCategories {
NSMutableArray* categorieTemp = [[NSMutableArray alloc] init];
unsigned count = [InhalteFromWeb count];
while (count--) {
NSString *tempString;
tempString=[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY];
NSLog(@"tempString %@", tempString );
[categorieTemp addObject:tempString];
}
NSSet *uniqueElements = [NSSet setWithArray:categorieTemp];
NSLog(@"categories from engine %@", categorieTemp);
NSArray* tempAr = [[[NSArray alloc] initWithArray:[uniqueElements allObjects]]sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
return [NSMutableArray arrayWithArray:tempAr];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
[categorieTemp containsObject:tempString]
检查现有字符串,并使用[categorieTemp sortUsingComparator:...]
对其进行排序示例:
Check for existing String with
[categorieTemp containsObject:tempString]
and sort it with[categorieTemp sortUsingComparator:...]
Example:
我这样做是为了对数组进行日期排序:
I do this to sort my array for a date: