簡體   English   中英

排序IP地址

[英]Sort IP address

我正在研究可掃描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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM