-2

我必须使用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
)}

所以我想我需要对它们进行排序以获得想要的结果?但我真的找不到任何例子。

也许有人可以帮助我吗?

谢谢。

编辑: 我不能使用其他。只是NSMutableSetNSSet

4

6 回答 6

3

正如其他人所说,NSSet根据定义未分类。但是,如果您必须使用NSMutableSet ,您可以使用类似的东西从元素中获取排序数组(假设在这种情况下元素是字符串)

NSArray* unsorted = [mySet allObjects];
NSArray* sorted = [unsorted sortedArrayUsingComparator: ^(NSString* string1, NSString* string2)
                   {
                       return [string1 localizedCompare: string2];
                   }];
于 2012-03-13T15:15:34.153 回答
2

如果说 NSSet 有什么特点,那就是它们没有任何顺序!

您应该为您的目的使用 NSMutableArray。

在此处阅读有关收藏的信息,它将对您有所帮助

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Collections.html#//apple_ref/doc/uid/10000034-BBCFIHFH

于 2012-03-13T15:00:52.857 回答
1

'NSSet' 是无序的。它意味着只包含唯一的项目(没有重复的项目)。来自 NSSet 的 Apples 文档:

...声明无序对象集合的编程接口。

如果您要订购,请选择NSMutableArrayNSMutableOrderedSet

于 2012-03-13T15:05:30.110 回答
1

试试这个

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);
于 2013-02-02T08:04:32.380 回答
0

NSMutableSet根据定义是无序的。对不起。

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableSet_Class/Reference/NSMutableSet.html

于 2012-03-13T15:01:15.110 回答
0

根据定义,集合是无序的。您需要使用 MacOS X 10.7 或更高版本中可用的 NSMutableOrderedSet 或 NSOrderedSet 的有序集。

于 2012-03-13T15:01:47.363 回答