Warning : "Sending 'NSObject *' to parameter of incompatible type 'id<NSCopying>'

AC Mohan picture AC Mohan · Jan 31, 2014 · Viewed 7.1k times · Source

I am struck in this warning for many hours... Am getting

The code is,

-(NSMutableDictionary*)iOSDiction
        {
            NSMutableDictionary *tmpDic = [[NSMutableDictionary alloc] initWithCapacity:[m_coordDic count]];
            for (NSObject *key in [m_coordDic allKeys]) 
            {
                [tmpDic setObject:[m_coordDic objectForKey:key] forKey:key];  //Warning
            }
            return tmpDic;
        }

Warning :

"Sending 'NSObject *' to parameter of incompatible type 'id'

Passing argument to parameter aKey here

NSDictionary.h

- (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey;

Answer

Roshan picture Roshan · Jan 31, 2014

NSDictionary keys should conform to NSCopying protocol. It is a basic requirement of a key as specified in the NSDictionary reference. In general, NSObject does not conform to the protocol(its subclasses might), so you are getting a warning. The correct way to do this is

NSMutableDictionary *tmpDic = [[NSMutableDictionary alloc] initWithCapacity:[m_coordDic count]];
for (NSObject<NSCopying> *key in [m_coordDic allKeys]) 
{
    [tmpDic setObject:[m_coordDic objectForKey:key] forKey:key];  //Warning
}
return tmpDic;

This ensures your key is any object confirming to NSCopying protocol.

EDIT: It seems what you are really trying to do is simply [m_coordDic mutableCopy], a shallow copy. Any reason you are not doing this?