2014-12-02 86 views
1

我有一個問題,我使用NSMutableDictionaries從NSDictionary返回值。iOS不兼容的指針類型從NSMutableDictionary返回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; 

} 

請幫我解決這個警告。

+0

如果你返回一個'NSDictionary'('return [NSDictionary ZzZ')),你爲什麼要設置一個'NSMutableDictionary'作爲你的方法的返回值(there:' - (NSMutableDictionary *)dictionaryZzZ')? – Larme 2014-12-02 09:33:18

+0

你應該返回[NSMutableDictionary dictionaryWithDictionary:_your_NSDictionary_]; – larva 2014-12-02 09:35:36

回答

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成一個可變的版本,而在第二種情況下,二手呼籲NSMutableDictionary子類dictionaryWithContentsOfFile方法而不是NSDictionary父類。

+0

感謝您的輸入。 – kart 2014-12-02 10:09:20