【问题标题】:I have to create a mutable dictionary but i am getting an "Incompatible pointer types initializing" error我必须创建一个可变字典,但我收到“不兼容的指针类型初始化”错误
【发布时间】:2023-03-28 19:36:01
【问题描述】:

我正在尝试创建一个字典,其中包含一个值为“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;
}

【问题讨论】:

    标签: ios objective-c dictionary mutable


    【解决方案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],
                                                    }];
    

    【讨论】:

    • 如果这解决了您的问题,请您将其标记为正确答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2014-03-19
    相关资源
    最近更新 更多