ios - 排序 IP 地址

标签 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

最佳答案

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

关于ios - 排序 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44342573/

相关文章:

java - 如何判断2个不同的单词是否具有相同的字母?

objective-c - 用于 RESTful API 的 XML 解析器

ios - 如何制作像谷歌地图应用程序那样的向上滑动面板?

iphone - 如果 UIActivityIndi​​catorView 被移除/释放/解除分配,它是否会自行停止动画

iphone - 如何使用 iOS 5 的 iOS TWRequest 获取 Twitter 用户详细信息

Java 快速添加和排序列表的方法

ruby - 如何按降序对数组进行排序?

ios - 当我导出我的 IOS PhoneGap 应用程序以进行临时分发时,如何使我的图标出现在我的 IOS PhoneGap 应用程序上?

ios - 绘制的图像不会出现在相机覆盖 Swift 上

ios - iOS 应用程序的远程访问