2016-09-25 21 views
0

我想創建一個包含值爲'Object_Info'的鍵的字典。 我有下面的代碼,並得到這個錯誤:我必須創建一個可變字典,但我得到一個「不兼容的指針類型初始化」錯誤

Incompatible pointer types initializing 'NSMutableDictionary *' with an expression of type 'NSDictionary *' 

這裏是我的代碼:

#import <Foundation/Foundation.h> 

@interface Object_Info : NSObject 
{ 
    NSString *product; 
    float cost; 
    int qty; 
} 
@end 


@implementation Object_Info 

-(id) init { 
    if (self = [super init]){ 
     product = @""; 
     cost = 0.0; 
     qty = 0;  
    } 
    return self; 
} 
@end 

int main(int argc, const char * argv[]) { 
    @autoreleasepool { 
      NSMutableDictionary *stock = @{ //ERROR IS HERE!!!!! 
           @"Lawn Chair" : [Object_Info new], 
           @"Beach Chair" : [Object_Info new], 
           @"Kitchen Chair" : [Object_Info new], 
           @"Futon" : [Object_Info new], 
           }; 

     for(NSString *key in [stock allKeys]) { 
      NSLog(@"%@",[stock objectForKey:key]); 
     } 

    } 
    return 0; 
} 

回答

1

您遇到的問題是,你正在嘗試一個NSDictionary分配到的NSMutableDictionary。

試試這個:

NSMutableDictionary *stock = [NSMutableDictionary new]; 
[stock setDictionary:@{ 
               @"Lawn Chair" : [Object_Info new], 
               @"Beach Chair" : [Object_Info new], 
               @"Kitchen Chair" : [Object_Info new], 
               @"Futon" : [Object_Info new], 
               }]; 
+0

如果這解決了你的問題,你可以將其標記爲正確的答案,請 – HarmVanRisk

相關問題