iOS 比较 NSArray 中 NSString 的 intValue

发布于 2024-12-25 21:04:58 字数 431 浏览 3 评论 0原文

我有一个 dico NSDictionary 包含以下内容: { 123 = , 125 = , ... 73 = 123

, 125, .., 73 是 NSString。

我想要一个包含按 id 排序的对象的 NSArray:

[ <MyObject:73>, <MyObject:123>, ..., <MyObject:125> ]

最有效的方法是什么?

我使用 [[dico allKeys]sortedArrayUsingSelector:@selector(compare:)] 来键入有序键列表,但由于键是 NSString,它们的排序方式不正确(我最终可能会得到 [ 42、46、5、56....]。

I have a dico NSDictionary containing things like:
{
123 = ,
125 = ,
...
73 =
}

123, 125, .., 73 are NSString.

I'd like to have an NSArray containing the objects ordered by their id:

[ <MyObject:73>, <MyObject:123>, ..., <MyObject:125> ]

What is the most efficient way to do so ?

I used [[dico allKeys] sortedArrayUsingSelector:@selector(compare:)] to key a list of ordered keys but as the keys are NSString they are not ordered the right way (I could end up with [ 42, 46, 5, 56. ...].

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你的他你的她 2025-01-01 21:04:58

当对代表数字的 NSString 进行排序时,您希望使用 NSNumericSearch 选项将它们像数字一样排序,例如 1 < > 20< 100< 1000。这是一个例子:

    NSMutableDictionary* d = [NSMutableDictionary dictionaryWithCapacity:3];
    [d setObject:@"C" forKey:@"3"];
    [d setObject:@"A" forKey:@"1"];
    [d setObject:@"B" forKey:@"2"];

    NSArray* sortedKeys = [d keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];

    NSLog(@"%@",sortedKeys);

    NSArray* sortedObjs = [d objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];
    NSLog(@"%@", sortedObjs);

When sorting NSStrings that represent numbers you want to use the NSNumericSearch option to sort them like numbers, e.g. 1 < 20 < 100 < 1000. Here's an example:

    NSMutableDictionary* d = [NSMutableDictionary dictionaryWithCapacity:3];
    [d setObject:@"C" forKey:@"3"];
    [d setObject:@"A" forKey:@"1"];
    [d setObject:@"B" forKey:@"2"];

    NSArray* sortedKeys = [d keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];

    NSLog(@"%@",sortedKeys);

    NSArray* sortedObjs = [d objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];
    NSLog(@"%@", sortedObjs);
暗藏城府 2025-01-01 21:04:58

您可以使用 NSDictionary 的 keysSortedWithCompartor 方法,在其中您可以提供一个比较器来以您希望的方式比较键(在您的情况下,通过将它们作为整数进行比较)。

You could use the keysSortedWithCompartor method of your NSDictionary, where you can supply a comparator to compare the keys whatever way you wish (in your case, by comparing them as integers).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文