jjzjj

ios - 设置对象 :forKey: of NSMutableDictionary overwrites all data in dictionary

coder 2024-01-21 原文

for ( int cnt = 0 ; cnt < nPeople ; cnt++ )
{
    ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, cnt);

    NSString    *firstName  = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
    NSString    *lastName   = (NSString *)ABRecordCopyValue(ref, kABPersonLastNameProperty);
    NSString    *fullName;   

    /* skipped code at here : code to merge firstName and lastName to fullName. In my country, many of us don't separate first name and last name */

    // tempKeyString : NSString variable that has key of fullNameArray value for nameDictionary.
    // fullNameArray : to keep some fullName variables for tempKeyString.
    if (!tempKeyString) // there's no tempKeyString, a.k.a. it's the first fullName.
    {
        // it's not important to know about GetUTF8String:fullName. It's for my own language.
        tempKeyString = [self GetUTF8String:fullName];
        [fullNameArray addObject:fullName];
    }
    else
    {
        if ([tempKeyString characterAtIndex:0] == [[self GetUTF8String:fullName] characterAtIndex:0]) // if fullName has the same tempKey with fullNameArray.
        {
            [fullNameArray addObject:fullName];
        }
        else // if fullName has different tempKey with fullNameArray.
        {
            //tempKey : key data for fullNameArray
            NSString    *tempKey    = [tempKeyString substringToIndex:1];
            // tempDict : to keep the deep copy of nameDictionary before adding new key.
            NSDictionary *tempDict   = [nameDictionary mutableDeepCopy];
            // add new key (tempKey) with new value (fullNameArray)
            // PROBLEM : ALL values (including previous values) in dictionary(nameDictionary) are overwritten to a new value(fullNameArray).
            [nameDictionary setObject:fullNameArray forKey:tempKey];

            //empties fullNameArray so that it can get the new fullName of the new tempKey.
            [fullNameArray removeAllObjects];
            //refresh tempKeyString, and add the new fullName.
            tempKeyString = [self GetUTF8String:fullName];
            [fullNameArray addObject:fullName];
            ...
        }
    }
}

我正在尝试从我的 iPhone 的联系人中创建一个 NSMutableDictionary 对象。为什么我制作一个 NSMutableDictionary 类型的对象是因为我需要联系人的索引,而且直接从 ABAddressRef 类型的对象制作索引看起来并不容易。我还需要做搜索功能..

我刚编码的时候没有问题,但调试后唯一的问题让我抓狂。在我将名为 fullNameArray 的数组和名为 tempKey 的键应用于 namedDictionary 之后,我可以发现 nameDictionary 具有 fullNameArray 的所有值。 所有以前的数据都被覆盖了!在应用 fullNameArray 并将其复制到较新的 nameDictionary 之前,我尝试对以前的 nameDictionary 进行深度复制。但是,当我检查第三行的断点时,我在tempDict中找不到之前的数据。

我添加了更多代码和注释。它可能比我的解释更有帮助..任何问题都很高兴!

我试图从这里-StackOverflow-和其他网页找了一晚上的原因,但我找不到任何类似的问题..请帮助我!非常感谢您!!

最佳答案

之所以清空是因为

[nameDictionary setObject:fullNameArray forKey:tempKey];

在这里,您使用对象“fullNameArray”设置字典,然后

[fullNameArray removeAllObjects];

删除这个数组中的所有值,有效地删除“nameDictionary”中的对象,它们是同一个对象,它不是存储在字典中的 fullNameArray 的深拷贝。为什么你需要将任何东西存储到你的数组中?您只存储 1 个值。

[nameDictionary setObject:fullName forKey:tempKey];

会做你需要的。对不起,如果我弄错了你的问题,这很难理解

关于ios - 设置对象 :forKey: of NSMutableDictionary overwrites all data in dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8998125/

有关ios - 设置对象 :forKey: of NSMutableDictionary overwrites all data in dictionary的更多相关文章

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

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

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

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

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

  5. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  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-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中的所有其他对象

  9. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  10. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

随机推荐