2013-02-18 26 views
0

我有一个NSDictionaries数组。现在这个数组为了简单起见只包含两个字典。我的NSDictionaries数组只返回键和没有值的字典。我怎样才能解决这个问题?

当我逐句通过代码,每个NSDictionary被正确地创建和包含预期值 ...我访问该阵列(填充在我的模型)通过:

@property (nonatomic, retain) NSMutableArray *sDictionaries;

我通过访问该属性在我的控制器:

NSArray *array = [[NSArray alloc]initWithArray:sLocator.sDictionaries]但是当我进去看看array,它只包含关键字,值s(我在字典创建时已经看到了这个字典)。

任何帮助将NSDictionary对象从我的模型传递到我的控制器非常感谢!

编辑:这里是我通过一些接收到的数据迭代并将其放置在NSDictionary对象中的代码。

NSMutableArray *arrayOfObjects = [[NSMutableArray alloc]initWithCapacity:0]; 
sDictionaries = [[NSMutableArray alloc]initWithCapacity:0]; 

int i = 0; 
//iterate through each element, get the string, then add to the array 
//I know for this example I am receiving 10 element objects which are NSStrings. 
//The first string is the key of the dictionary and the next 4 strings are the values. 
//Then all the objects are removed from arrayOfObjects and a new dictionary is made 
for(Element *element in nodes) 
{ 
    [mArray addObject:[element content]]; 

    if(i%5 != 0) 
    { 
     [arrayOfObjects addObject:[element content]]; 
    } 

    if(i%5 == 0) 
    { 
     [idArray addObject:[element content]]; 
    } 

    if([arrayOfObjects count] >= 4) 
    { 
     //Here is where the dictionary is created then added to the array. 
     NSDictionary *dictionary = [NSDictionary dictionaryWithObject:arrayOfObjects forKey:[idArray lastObject]]; 
     [sDictionaries addObject:dictionary]; 

     [arrayOfObjects removeAllObjects]; 
    } 

    i++; 
} 
+0

如何创建和填充'sDictionaries'? – coverback 2013-02-18 08:07:53

+0

你能检查一下吗? NSLog(@“class%@”,[[sLocator.sDictionaries] class])。可以是字典。 – thndrkiss 2013-02-18 08:09:15

+0

@trojanfoe - 我只做一次,而不是多次。我也尝试过'NSArray * array = sLocator.sDictionaries'。 @coverback - 像这样: '的NSDictionary *词典= [NSDictionary的dictionaryWithObject:arrayOfObjects forKey:[idArray lastObject]];' '[sDictionaries ADDOBJECT:辞典];' 'arrayOfObjects'仅仅是一个可变的数组包含4个字符串。 'idArray'也是一个包含字符串的可变数组。 @thndrkiss - 是的,明天早上我会检查,我整天都在做这个项目,现在我打电话给它退出。我会让你知道当我检查 – 2013-02-18 08:17:46

回答

2

我觉得这一行很糟糕。 NSDictionary *dictionary = [NSDictionary dictionaryWithObject:arrayOfObjects forKey:[idArray lastObject]];

将所有对象添加到字典后删除了所有对象,因此它自己的对象被删除。尝试将该行更改为

NSDictionary *dictionary = [NSDictionary dictionaryWithObject:[NSArray arrayWithArray:arrayOfObjects] forKey:[idArray lastObject]];

+0

是的,我想要删除所有对象字典被创建。如果我在删除之前创建它,字典是否不再依赖'arrayOfObjects'的内容? 我会给你建议一个尝试。 – 2013-02-19 00:33:59

+0

@JohnnyGamez:它不再依赖于变量*'arrayOfObjects'的*值 - 也就是说,如果您为变量指定了一个新数组,该字典将不会在意 - 但它仍然依赖于*的内容数组本身*。所以当你改变数组的内容时(比如通过“removeAllObjects”),它会影响包含字典在内的所有引用的数组。 – Chuck 2013-02-19 00:50:34

+0

谢谢@onevcat!这解决了我的问题。 我想我对'NSDictionary'对象如何保留它们的值有一个误解。我将不得不查看关于这个东西的文档。 – 2013-02-19 05:12:17

相关问题