[英]iOS: 'NSInvalidArgumentException', reason: '-[__NSCFString sortedArrayUsingFunction:context:]: unrecognized selector sent to instance.
I get the following crash when trying to get the first 10 sets of keys. 尝试获取前10组键时出现以下崩溃信息。 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];
但是,当我仅使用此
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.
我只想要前10个键。
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. 这意味着,
allKeys
可以在任何时候以任何顺序返回。 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.
如果使用我上面提供的代码,您将获得10个键的排序数组。 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)];
You are getting the crash because [answers allkeys][i]
is returning an NSString . 由于
[answers allkeys][i]
返回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)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.