OGeek|极客世界-中国程序员成长平台

标题: ios - 将 NSDictionary 传递给函数以添加对象/键,但在 main() 中显示为空 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 02:16
标题: ios - 将 NSDictionary 传递给函数以添加对象/键,但在 main() 中显示为空

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

-(BOOL) addThingThing*)myThing withKeyNSString*)key inDictionaryNSMutableDictionary*) 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 方法中进行计数检查,它将打印“我不是空的!”。我不确定我做错了什么。



Best Answer-推荐答案


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

确实有效的方法是:

- (BOOL) addThingid)thing withKeyNSString *)key inDictionaryNSMutableDictionary **)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 转换为非零字典,前提是您没有传递将包含对象 foo< 的零 keything/code> 用于键 @"key"

我测试了,没有错误。

关于ios - 将 NSDictionary 传递给函数以添加对象/键,但在 main() 中显示为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26086454/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4