Objective c 排序可变表集
我必须使用Objective c 排序可变表集,objective-c,ios,nsmutableset,Objective C,Ios,Nsmutableset,我必须使用NSMutableSet来存储字符串对象。我希望以正确的顺序存储它们,例如从最小到最大的数字: 1 2 3 4 如果你这样做: NSMutableSet *set = [[NSMutableSet alloc] init]; [set addObject:[NSString stringWithFormat:@"1"]]; [set addObject:[NSString stringWithFormat:@"2"]]; [set addObject:[NSString string
NSMutableSet
来存储字符串对象。我希望以正确的顺序存储它们,例如从最小到最大的数字:
1
2
3
4
如果你这样做:
NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObject:[NSString stringWithFormat:@"1"]];
[set addObject:[NSString stringWithFormat:@"2"]];
[set addObject:[NSString stringWithFormat:@"3"]];
[set addObject:[NSString stringWithFormat:@"4"]];
NSLog(@"set is %@",set);
[set release];
我没有得到我想要的,而是:
set is {(
3,
1,
4,
2
)}
所以我想我需要对它们进行排序以得到想要的结果?但我真的找不到任何例子
也许有人能帮我
谢谢
编辑:
我不能用别的。只要
NSMutableSet
或NSSet
就行了,如果NSSet的任何特征是它们没有任何顺序
您应该使用NSMutableArray
在这里阅读有关收藏的信息,它将对您有所帮助
根据定义,NSMutableSet是无序的。对不起
集合按定义是无序的。使用MacOS X 10.7或更高版本中提供的NSMUTABLEORDEDSET或NSORDERDSET,您需要一个有序集。一个“NSSet”是无序的。它仅包含唯一项(无重复项)。从NSSet的苹果文档: …向对象的无序集合声明编程接口
如果您想要订购,请选择
NSMutableArray
或NSMutableOrderedSet
正如其他人所说,NSSet
根据定义是未排序的。但是,如果有要使用NSMutableSet
,则可以使用以下内容从元素中获得排序数组(假设在本例中元素是字符串)
试试这个
NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObject:[NSString stringWithFormat:@"1"]];
[set addObject:[NSString stringWithFormat:@"2"]];
[set addObject:[NSString stringWithFormat:@"3"]];
[set addObject:[NSString stringWithFormat:@"4"]];
NSLog(@"%@",set); // Output (3,1,4,2,5) ... all objects
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
NSArray *sortedArray = [set sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
NSLog(@"%@",sortedArray);
我不能用别的。只是NSMutableSet或NSSET为什么不能改用NSMUTABLEORDEDSET或NSORDERDSET?您是如何使用@“描述”的?那是什么?
NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObject:[NSString stringWithFormat:@"1"]];
[set addObject:[NSString stringWithFormat:@"2"]];
[set addObject:[NSString stringWithFormat:@"3"]];
[set addObject:[NSString stringWithFormat:@"4"]];
NSLog(@"%@",set); // Output (3,1,4,2,5) ... all objects
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
NSArray *sortedArray = [set sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
NSLog(@"%@",sortedArray);