我正在开发一个扫描 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
最佳答案
使用 ip3thOctet
中的 objectAtIndex:elements-1
,您正在访问最后一个元素(从 0 开始计数)。所以你两次都在为最后一个元素排序。您应该使用 elements-2
。
关于ios - 排序 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44342573/