iOS不兼容的指针类型从NSMutableDictionary返回NSDictionary

时间:2014-12-02 09:27:52

标签: ios xcode nsdictionary

我遇到的问题是我使用NSMutableDictionaries从NSDictionary返回值。

以下是警告信息:

  

不兼容的指针类型从函数返回'NSDictionary *'   结果类型为'NSMutableDictionary *'

以下是代码:

- (NSMutableDictionary *)dictionaryWithContentsAtPath:(NSString *)path 

{

if ([path rangeOfString:@"/SessionStore"].location == 0) 
{

return [_inMemoryCache objectForKey:[path stringByReplacingCharactersInRange:NSMakeRange(0, 13) withString:@""]];

}

if ([path rangeOfString:@"/PermanentStore"].location == 0) 

{

return [NSDictionary dictionaryWithContentsOfFile:[self.persistentStoragePath stringByAppendingPathComponent:[path substringFromIndex:15]]];

}

return nil;

}

请帮我解决此警告的方法。

1 个答案:

答案 0 :(得分:1)

您需要确保返回正确的类型。您的方法声明它返回NSMutableDictionary,但之后只返回NSDictionary

请改为尝试:

- (NSMutableDictionary*)dictionaryWithContentsAtPath:(NSString*)path {

    if ([path rangeOfString:@"/SessionStore"].location == 0) {
        return [[_inMemoryCache objectForKey:[path stringByReplacingCharactersInRange:NSMakeRange(0, 13) withString:@""]] mutableCopy];
    }

    if ([path rangeOfString:@"/PermanentStore"].location == 0) {
        return [NSMutableDictionary dictionaryWithContentsOfFile:[self.persistentStoragePath stringByAppendingPathComponent:[path substringFromIndex:15]]];
    }

    return nil;
}

注意:添加了对mutableCopy的调用以将您的文字NSDictionary转换为可变版本,而在第二种情况下,在dictionaryWithContentsOfFile上使用了NSMutableDictionary方法子类而不是NSDictionary父类。