从NSDictionary中检索值

时间:2012-07-24 21:13:05

标签: iphone ios nsdictionary

我正在尝试从我的NSDictionary中检索值但是我遇到了错误,我想知道是否有人可以帮我解决问题。

我有18个值,这里没有显示我正在检查的所有值,当到达正确的键时,我想获取NSDictionary中的值并将其传递给我的一个NSString变量。

下面是我想要做的一个例子,但就像我说我有几个问题

for (id key in searchData) {
    if ([[searchData objectForKey:key] isEqualToString:@"Code"]) {
        codeSeries = [searchData objectForKey:key];
    }
    else if ([[searchData objectForKey:key] isEqualToString:@"ID"]) {
        IDSeries = [searchData objectForKey:key];
    }

    // ...

但是,当我尝试注销任何值时,它们都会返回Null。我事先检查了字典,并且值肯定都在那里,所以我认为上面的代码有问题。

非常感谢任何帮助。

更新

这就是我创建NSDictionary的方式

//start of mymethod...

NSDictionary *sendSeriesDictionary = [[NSDictionary alloc] init];

    // Keys for sendSeriesDictionary
    NSArray *keys = [NSArray arrayWithObjects:@"Code", @"ID", nil];

    // Objects for keys that are for sendSeriesDictionary
    NSArray *objects = [NSArray arrayWithObjects: [NSNull null], IdString, nil];

    // Add keys and objects to NSDictionary
    sendSeriesDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];


[engineRequests SeriesSearch:sendSeriesDictionary]; // this is where I send the NSDictionary over to where I want to read it.

//end of mymethod

2 个答案:

答案 0 :(得分:1)

你在混合键和值吗?

也许你只想要codeSeries = [searchData objectForKey:@"Code"];

答案 1 :(得分:1)

你有几个问题。首先,你混淆了键和值(就像汤姆所说)。其次,在创建字典时可能存在内存泄漏,或者至少是不必要的实例化。

尝试使用此方法创建字典:

// Keys for sendSeriesDictionary
NSArray *keys = [NSArray arrayWithObjects:@"Code", @"ID", nil];

// Objects for keys that are for sendSeriesDictionary
NSArray *objects = [NSArray arrayWithObjects: [NSNull null], IdString, nil];

// Add keys and objects to NSDictionary
NSDictionary *sendSeriesDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

检索值可以这样做:

codeSeries = [searchData objectForKey:@"Code"];
IDSeries = [searchData objectForKey:@"ID"];

在你的第一个循环中,你循环遍历所有键,得到它们的值,然后再将它们与键进行比较。这毫无意义。

相关问题