排序IP地址

时间:2017-06-03 09:44:51

标签: ios iphone sorting networking ip

我正在研究扫描wi-fi网络的应用程序并列出ip列表和连接的设备。

我尝试通过创建两个新的对象属性ip4thOctet和ip3thOctet来对ip列表进行排序,并在依赖它们之后进行排序。

@property (nonatomic, assign) NSInteger ip4thOctet;
@property (nonatomic, assign) NSInteger ip3thOctet;

和:

-(NSInteger)ip4thOctet {
    if (self.ipAddress) {
            return [[[self.ipAddress componentsSeparatedByString:@"."] lastObject] intValue];
    }
    return 0;
}

-(NSInteger)ip3thOctet {
    if (self.ipAddress) {
        NSInteger elements = [[self.ipAddress componentsSeparatedByString:@"."] count];
        return [[[self.ipAddress componentsSeparatedByString:@"."] objectAtIndex:elements-1] intValue];
    }
    return 0;
}

基于这些属性,我试图对数组进行排序:

-(void)lanScanDidFindNewDevice:(Device*)device {
    if (![connectedDevicesMutable containsObject:device]) {
        [connectedDevicesMutable addObject:device];
    }

    self.connectedDevices = [NSMutableArray arrayWithArray:connectedDevicesMutable];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"ip4thOctet"
                                                 ascending:YES
                                                  selector:@selector(compare:)
                      ];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    self.connectedDevices = [self.connectedDevices sortedArrayUsingDescriptors:sortDescriptors];


    NSSortDescriptor *sortDescriptor3thIpOctect = [[NSSortDescriptor alloc] initWithKey:@"ip3thOctet"
                                                 ascending:YES
                                                  selector:@selector(compare:)
                      ];
    NSArray *sortDescriptors3th = [NSArray arrayWithObject:sortDescriptor3thIpOctect];
    self.connectedDevices = [self.connectedDevices sortedArrayUsingDescriptors:sortDescriptors3th];
}

客户预期结果如下:

预期:

172.17.0.1

172.17.0.2

172.17.1.1

172.17.1.3

172.17.3.1

你能帮我按照客户的期望对ip列表进行排序吗?

目前的结果是:

172.17.0.1

172.17.1.1

172.17.3.1

172.17.0.2

172.17.1.2

172.17.0.3

172.17.1.3

1 个答案:

答案 0 :(得分:1)

objectAtIndex:elements-1中的ip3thOctet您正在访问最后一个元素(从0开始计数)。所以你们都要为最后一个元素排序。您应该使用elements-2