Tyrone Prude
Tyrone Prude

Reputation: 382

Sort IP address

I'm working on an application which scan the wi-fi network and list the ip list and device connected.

I tried to sort the ip list by creating two new object properties ip4thOctet and ip3thOctet and make the sort after depend of them.

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

and:

-(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;
}

Based on these properties I tried to sort the array:

-(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];
}

The client expected result should looks like :

Expected:

172.17.0.1

172.17.0.2

172.17.1.1

172.17.1.3

172.17.3.1

Can you help me to sort the ip list according with client expectation, please ?

The current result is :

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

Upvotes: 0

Views: 274

Answers (1)

Gerriet
Gerriet

Reputation: 1350

With objectAtIndex:elements-1 in ip3thOctet you are accessing the last element (start counting at 0). So you are both times sorting for the last element. You should use elements-2.

Upvotes: 1

Related Questions