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

标签 ios objective-c pointers nsdictionary

我是 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 keything,其中将包含对象 foo 为键 @"key"

我测试过,没有发现错误。

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

相关文章:

android - iOS 和 Android 允许什么样的应用程序代码混淆?

ios - 平滑地旋转刷新按钮图像,使其完成到最近的转角 iOS

objective-c - 在 NSTableView 文本单元格中创建和响应超链接

objective-c - GCD 等待队列中的所有任务完成

c# - 泛型指针

ios - Xcode 中是否可以对不同的手机尺寸有不同的约束?

ios - Swift 中的三角函数

objective-c - NSUrlSession 代理请求失败,错误代码为 310 (kCFErrorHTTPSProxyConnectionFailure)

c - 当将指针强制转换为指向包含 union 的结构时

c - C 实现双端队列时出现段错误