Sorting NSMutableSet
-
13-12-2019 - |
Frage
I have to use NSMutableSet
to store my string objects. I wan to store them in right order for example from smallest to biggest number:
1
2
3
4
How ever if do this:
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];
I don't get what i wanted but instead this:
set is {(
3,
1,
4,
2
)}
So I guess i need to sort them to get wanted result ? But really i can't find any example.
Maybe someone could help me on this ?
Thanks.
EDIT:
I can't use else. Just NSMutableSet
or NSSet
Lösung
If there's any characteristic of the NSSet is that they dont have any order!
You should use a NSMutableArray for your purpose.
Read about collections here, it will help you
Andere Tipps
As everybody else has said, NSSet
is unsorted by definition. Howeever, if you have to use NSMutableSet
you can get a sorted array from the elements using something like (assuming, in this case the elements are strings)
NSArray* unsorted = [mySet allObjects];
NSArray* sorted = [unsorted sortedArrayUsingComparator: ^(NSString* string1, NSString* string2)
{
return [string1 localizedCompare: string2];
}];
An 'NSSet' is unordered. It is meant to contain only unique items (no duplicate items). From Apples docs of NSSet:
...declare the programmatic interface to an unordered collection of objects.
If you want order, go for NSMutableArray
or NSMutableOrderedSet
.
try this
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
is by definition unordered. Sorry.
Sets are unordered by definition. You need an ordered set by using NSMutableOrderedSet or NSOrderedSet which are available in MacOS X 10.7 or later.