Reputation: 171
I get the following crash when trying to get the first 10 sets of keys. Here is the code that is causing the problem.
for (int i = 0; i < 10; i++) {
sortedArray = [ [answers allKeys][i] sortedArrayUsingFunction:sort context:nil];
}
However, when I just use this sortedArray = [ [answers allKeys] sortedArrayUsingFunction:sort context:nil];
I do not get a crash. Can someone please help me figure out how to fix this? I just want the first 10 keys.
Upvotes: 0
Views: 205
Reputation: 53132
I'm just guessing here, but I think you want this.
NSArray *arr = [[answers allKeys] subarrayWithRange:NSMakeRange(0, 10)];
NSArray *sorted = [arr sortedArrayUsingFunction:sort context:nil];
Unfortunately, this won't work and you will need to change your architecture. Here's why.
Dictionaries are unordered. That means, allKeys
could come back in any order at any point. Particularly the way you have it where you're iterating, it's not likely, but it's possible that you'll have an array filled with all the same key. If you use the code I provided above, you'll get a sorted array of 10 keys. While these keys will be unique, they will not be determined by any order and should be assumed to be random.
Perhaps you need to sort your keys before filtering out your array? That could look something like this:
NSArray *sorted = [[answers allKeys] sortedArrayUsingFunction:sort context:nil];
NSArray *filtered = [sorted subarrayWithRange:NSMakeRange(0, 10)];
Upvotes: 2
Reputation: 5095
You are getting the crash because [answers allkeys][i]
is returning an NSString.
Perhaps what you are trying to do can be accomplished like this:
NSArray* sortedArray = [[answers allKeys] sortedArrayUsingFunction:sort context:nil];
NSArray* sorted1st10 = [sortedArray subarrayWithRange:NSMakeRange(0, 10)];
Upvotes: 0