草庐IT

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

coder 2024-01-24 原文

我是 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 ** 传递给您的函数,并将其视为指针,也就是说,将其用作 *我的字典

确实有效的方法是:

- (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]

如果你没有传递 nil keything,这确实会将 dict 变成一个非 nil 字典,它将包含对象 foo@"key"

我测试过没有错误。

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

有关ios - 将 NSDictionary 传递给函数以添加对象/键,但在 main() 中显示为空的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  3. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  4. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  5. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  6. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  7. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  8. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  9. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  10. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

随机推荐