将NSDictionary传递给函数以添加对象/键但在main()中显示为空

我是Objective C的新手,我在添加到我的NSMutableDictionary时遇到了问题。 我有一个包含以下方法的Thing类。

-(BOOL) addThing:(Thing*)myThing withKey:(NSString*)key inDictionary:(NSMutableDictionary*) myDictionary { if(!myDictionary) { //lazy initialization myDictionary = [NSMutableDictionary dictionary]; [myDictionary setObject:myThing forKey:key]; return YES; } else { if(![myDictionary allKeysForObject: _monster]) { [myDictionary setObject:record forKey:key]; return YES; } else { NSLog(@"The username %@ already exists!", _monster); return NO; } } 

}

但是当我在main()中调用它时,字典仍然显示为空。

 int main(int argc, const char * argv[]) { @autoreleasepool { NSMutableDictionary *myDictionary; Thing *foo = [Thing thingWithName:@"Frankenstein" andFeature:@"green"]; [foo addThing:foo withKey:@"foo" inDictionary:myDictionary]; if([myDictionary count] > 0) { NSLog(@"I'm not empty!"); } else { NSLog(@"Dictionary is empty"); } //Prints out "Dictionary is empty" } return 0; 

}

如果我直接在我的addThing方法中检查,它将打印“我不是空的!”。 我不确定我做错了什么。

你的问题是你只是在addThing:withKey:inDictionary初始化局部变量addThing:withKey:inDictionary 。 为了能够影响您作为参数传递的NSDictionary ** ,您必须确实将NSDictionary **传递给您的函数,并将其视为指针,即将其用作*myDictionary

确实有用的东西是:

 - (BOOL) addThing:(id)thing withKey:(NSString *)key inDictionary:(NSMutableDictionary **)myDictionary{ if(!*myDictionary && key && thing){ *myDictionary = [NSMutableDictionary dictionary]; [*myDictionary setObject:thing forKey:key]; return YES; } else { // Removed this code as it doesn't really matter to your problem return NO; } } 

并调用它(注意传递dict变量的地址而不是普通变量):

 NSMutableDictionary *dict; [foo addThing:foo withKey:@"key" inDictionary:&dict] 

这确实会将dict转换为非零字典,只要你没有传递一个nil key或者thing ,它将包含key @"key"对象foo

我测试过没有错误。

即使这是客观C而不是普通C,您对该方法的调用仍然是按值调用,而不是通过引用调用。 您的方法调用[foo addThing:foo withKey:@“foo”inDictionary:myDictionary]创建指针myDictionary的副本,并将其发送到您的方法。 字典已创建然后丢失,因为此处没有机制将其复制回主函数中的真实myDictionary。 如果您仍然不确定,请按引用查询并按值调用。 在addThing方法中创建的myDictionary是原始myDictionary的副本,不会影响您的全局。