我是 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
中初始化局部变量 myDictionary
。
为了能够影响您作为参数传递的 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 字典,前提是您没有传递 nil key
或 thing
,其中将包含对象 foo
为键 @"key"
。
我测试过,没有发现错误。
关于ios - 将 NSDictionary 传递给函数以添加对象/键,但在 main() 中显示为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26086454/