简体   繁体   中英

Add a NSXPCConnection as a key to a NSMutableDictionary

Edit:

I solved this problem by adding the process identifier that is exposed from the NSXPCConnection class as that is unique per connection as the key.

Problem:

I'm facing a problem where I need to store a key-value pair in a NSMutableDictionary (where an object of type NSXPCConnection is stored as the key). But I'm unable to do so as NSXPCConnection does not conform to NSCopying.

This is my code:

- (void)addDataToDict:(MyClass *)obj Connection:(NSXPCConnection *)connection
{   
    assert(obj);
    
    LogInfo("Assert success");
    
    if([_dict objectForKey:connection])
    {
        LogError("Connection already in dictionary, abort");
        return;
    }
    else
        LogInfo("Adding connection to dict");
    
    NSObject<NSCopying> *key = connection;
    
    [_dict setObject:obj forKey:key];
}

But this throws the following warning:

Incompatible pointer types initializing 'NSObject<NSCopying> *' with an expression of type 'NSXPCConnection *'

and the following error during runtime:

-[NSXPCConnection copyWithZone:]: unrecognized selector sent to instance 0x127a4b0d0

Any suggestions on how I can do this better are welcome!

Although you've already solved this for your specific use-case by using a different key type, one alternative is to use an NSMapTable , which behaves very much like NSDictionary but allows you to have different semantics for keys and values.

Specifically, for this use-case, a +strongToStrongObjectsMapTable would be appropriate as it retains keys instead of copying them, allowing you to key by non- NSCopying objects like NSXPCConnection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM