使用IPv4地址对NSTableView列进行排序

时间:2012-03-01 14:26:40

标签: objective-c cocoa nstableview ipv4 nssortdescriptor

我想使用SortDescriptor对带有IPv4地址的NSTableView列进行排序。我到目前为止:

NSArray *devicesSortDescriptor = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"ip" ascending:YES comparator:^NSComparisonResult(id ipstring1, id ipstring2) {
        const char * ipch1 = [ipstring1 cStringUsingEncoding:NSASCIIStringEncoding];
        const char * ipch2 = [ipstring2 cStringUsingEncoding:NSASCIIStringEncoding];
        struct in_addr ip1, ip2;

        inet_aton(ipch1, &ip1);
        inet_aton(ipch2, &ip2);

        if (ip1.s_addr > ip2.s_addr)
            return NSOrderedDescending;
        else if (ip1.s_addr == ip2.s_addr)
            return NSOrderedSame;
        else
            return NSOrderedAscending;
    }]];

这就是结果:

strange sorted IPv4s

我做错了什么?我的意思是如果ip1.s_addr> ip2.s_addr然后它的原因是NSOrderedDescending .. o_O

谢谢!

1 个答案:

答案 0 :(得分:2)

我刚刚发现,你需要的只是一个数字比较器:

<强>目标-C:

comparator:^(NSString *a, NSString *b) {
        return [a compare:b options:NSNumericSearch];
    }   

<强>夫特:

comparator: {
        (a, b) -> NSComparisonResult in

        let result = a.compare(b as! String, options: NSStringCompareOptions.NumericSearch)
        return result
    }

:)