通过 lldb 在 NSMutableDictionary 中设置对象时出错

Error while setting object in NSMutableDictionary via lldb

调试时我需要替换不可变字典中的一个值。 为此,我从不可变的中创建了一个可变的字典,并尝试使用 lldb 命令为此设置一个值:

po NSMutableDictionary *$tmp = [(NSDictionary *) immutableDict mutableCopy]
po [$tmp setObject:@"object" forKey:@"key"]

但是 lldb 失败并出现错误:

error: cannot initialize a parameter of type 'id<NSCopying> _Nonnull' with an rvalue of type 'NSString *' passing argument to parameter 'aKey' here

有人知道如何解决这个问题吗?

这样走,

NSDictionary *dictTemp = [[NSDictionary alloc] initWithObjects:@[@"Value1",@"value2"] forKeys:@[@"Key1",@"Key2"]];
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] initWithDictionary:dictTemp];

用lldb输出,

Printing description of mutableDict:
{
    Key1 = Value1;
    Key2 = value2;
}
(lldb) po [mutableDict setObject:@"Value3" forKey:@"Key3"]
(lldb) po mutableDict
{
    Key1 = Value1;
    Key2 = value2;
    Key3 = Value3;
}

(lldb) 

你应该使用这个脚本:

expression [mutableDict setValue:@"newObject" forKey:@"key"];

这是setObject:forKey:定义:

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

密钥应遵循 NSCopying 协议。

setValue:forKey:定义:

- (void)setValue:(nullable ObjectType)value forKey:(NSString *)key;

class NSString.

的密钥种类

如果您 运行 在 Xcode 10 中遇到这个问题,调试器中似乎存在一个缺陷,有时(但并非总是)无法执行忠实于编译代码。它并不总是发生的事实使得当它确实发生时特别令人不安,而且关于它的文章很少。

我不完全了解细节,但幸运的是有一个简单的修复方法。 (至少每次我 运行 它对我有用。)只需将密钥的类型转换为 id,如下所示:

(lldb) expr check[(id)@"check_id"]= @"383027"
(NSTaggedPointerString *)  = 0xb0b97b49f6ae12f7 @"383027"