Home > OS >  objective C add keys to dictionary
objective C add keys to dictionary

Time:12-01

In the code snippet below you can find my current implementantion where the function return an array with data. I'm looking for a way to return an NSDictionary instead with "IPv4", "IPv6" keys and values correspondingly.

  (NSArray<NSString *> *) addressesFromService:(NSNetService *)service
{
//    NSMutableArray<NSString *> *addresses = [[NSMutableArray alloc] init];
    NSMutableDictionary<NSString *, NSString *> *result = [NSMutableDictionary dictionary];

    
    char addressBuffer[INET6_ADDRSTRLEN];
    
    for (NSData *data in service.addresses) {
        memset(addressBuffer, 0, INET6_ADDRSTRLEN);

        typedef union {
            struct sockaddr sa;
            struct sockaddr_in ipv4;
            struct sockaddr_in6 ipv6;
        } ip_socket_address;

        ip_socket_address *socketAddress = (ip_socket_address *)[data bytes];

        if (socketAddress && (socketAddress->sa.sa_family == AF_INET || socketAddress->sa.sa_family == AF_INET6)) {
            const char *addressStr = inet_ntop(
                socketAddress->sa.sa_family,
                (socketAddress->sa.sa_family == AF_INET ? (void *)&(socketAddress->ipv4.sin_addr) : (void *)&(socketAddress->ipv6.sin6_addr)),
                addressBuffer,
                sizeof(addressBuffer)
            );

//            if (addressStr) {
//                NSString *address = [NSString stringWithUTF8String:addressStr];
//                [addresses addObject:address];
//            }
            if (addressStr) {
                NSString *key = AF_INET ? @"IPv4" : @"IPv6";
                result[key] = [NSString stringWithUTF8String:addressStr];
            }
        }
    }

//    return [NSArray arrayWithArray:addresses];
    return [result copy];
}
    

CodePudding user response:

You'll need to adjust the method/function signature to match the return type (NSDictionary * instead of NSArray *) but for the snippet you provided you merely need to introduce a mutable dictionary right prior to the loop body:

NSMutableDictionary<NSString *, NSString *> *result = [NSMutableDictionary dictionary];
for (NSData *data in service.addresses) {
...

And then replace the part where you add values like this:

if (addressStr) {
    NSString *key = socketAddress->sa.sa_family == AF_INET ? @"IPv4" : @"IPv6";
    result[key] = [NSString stringWithUTF8String:addressStr];
}

If you want to return an immutable version of the dictionary, don't forget to make a copy:

return [result copy];
  • Related