【问题标题】:Objective-c NSMutableDictionary set with an array keep empty带有数组的Objective-c NSMutableDictionary集保持为空
【发布时间】:2015-07-15 04:12:11
【问题描述】:

我是新来的,但是当我需要一些东西时,我会阅读这个网站,但是今天,我找不到我的问题的答案。

我会尽量详细解释我的问题。

我需要在 NSMutableDictionary 的特定键处添加一个数组。添加到其中的键正确,但我的字典值保持为空。这是我的代码:

dictionarySection = [[NSMutableDictionary alloc] initWithObjects:arraySectionValues forKeys:arraySectionKeys];
dictionaryClip = [[NSMutableDictionary alloc] initWithCapacity:[arraySectionKeys count]];

NSArray *tabSection = [dictionarySection allKeys];
id key,value;
for (int j=0; j<tabSection.count; j++)
{
    array = [NSMutableArray array];
    key = [tabSection objectAtIndex: j];
    value = [dictionarySection objectForKey: key];
    //NSLog (@"Key: %@ for value: %@", key, value);
    for (SMXMLElement *clip in [books childrenNamed:@"clip"]) {
        if([[clip valueWithPath:@"categorie"] isEqualToString:value]){
            [array addObject:[clip valueWithPath:@"titre"]];
        }
    }
    NSLog(@"Test array %@",array);
    [dictionaryClip setObject:array forKey:key];
    [array removeAllObjects];
    NSLog(@"Test dictionary %@",dictionaryClip);
}

这里是 NSLog 结果:

2015-07-15 14:34:48.272 test[15533:390301] Test array (
"CDS : ITV Philippe Dunoyer",
"FLASH INFO NCI : crise des banques",
"Les Roussettes sont-elles dangereuses ?",
"Flash infos banques gr\U00e8ve",
"CDS : ITV Paul Langevin",
"CDS : ITV Valls",
"CDS : ITV Victor Tutugoro",
"CDS : ITV Roch Wamytan",
"NCGLAN 20",
"Flash Info : dispositif anti-d\U00e9linquance"
)
2015-07-15 14:34:48.273 test[15533:390301] key : 0
2015-07-15 14:34:48.273 test[15533:390301] Test dictionary {
    0 =     (
    );
}

如我们所见,数组已填满,字典的键是正确的,但数组不在我的字典中。

我应该如何用这个数组填充我的字典?

非常感谢大家的回答:)

Ps : 请原谅我的英语:(

【问题讨论】:

    标签: ios objective-c arrays dictionary nsmutabledictionary


    【解决方案1】:

    您正在为您在字典中传递的同一数组实例调用 removeAllObjects: 方法,因此它的对象正在存储数组中被删除。尝试传递该数组的副本或具有相同对象的数组的新实例。

    示例:

    [dictionaryClip setObject:[array copy] forKey:key];
    

    【讨论】:

    • 完美 我得到了我想要的 :) 非常感谢!!!我的名声太低了,不能给你一点意见:(但无论如何谢谢;)
    • 很高兴为您提供帮助! @vadian 也告诉过你,但因为你是新程序员,所以我解释了更多。 :) 快乐编码,你可以稍后给我积分。
    【解决方案2】:

    在 Objective-C 中,数组是引用类型。

    方法setObject:forKey:将指向数组的指针放入字典中,数组没有被复制。

    如果从数组中删除所有对象,它们也会在字典中消失

    【讨论】:

    • 好的,谢谢!我没想到这个!我会尝试另一种方式......如果你有一个想法可以帮助我,那就太好了:)
    • @Nicolas 也许只是复制数组? [dictionaryClip setObject:[array copy] forKey:key];这可能是最简单的解决方案,之后你就可以对原始数组做任何你想做的事情了。
    • @ user2194039 谢谢 :) 它有效 :) 非常感谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多