开发者

Undefined key when iterating through NSDictionary

I am pretty new to iPhone/Objective-c programming. I'm struggling with an issue that doesn't make sense to me. I am writing an app that, as part of the code, will consume restful services. The method I am writing to make Post calls, using the ASIHttpRequest library, looks like this:

- (NSString *) httpPostStringResponseUrl:(NSURL *)url:(NSDictionary *)args{
    ASIFormDataRequest  *request = [[[ASIFormDataRequest  alloc]  initWithURL:url] autorelease];

    NSArray *keys = [args allKeys];

    NSEnumerator *e = [args keyEnumerator];
    NSString* object;
    while (object = [e nextObject]) {
            NSLog(@"Adding to args key: %@", object);
        [request setPostValue:[keys valueForKey:object] forKey:object];
    }

    NSLog(@"Starting http POST request");
    [request startSynchronous];
    NSString *response = [request responseString];
    return response;
}

The idea is to pass in a dictionary of arguments and their values, and use them as the arguments to the POST request. However, when I run this code I get an NSUnknownKeyException.

This doesn't make sense to me. The only access to the dictionary I am doing is using the keys 开发者_如何学Goprovided by the iterator. So, how can they be part of the iterator and not be valid keys?

For completeness, here is the code where I call the above function:

NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
NSURL *url = [[[NSURL alloc] initWithString:@"http://myURL"] autorelease];

[params setValue:@"user" forKey:@"Username"];
[params setValue:@"1234" forKey:@"Password"];

NSString *response = [web httpPostStringResponseUrl:url :params];

NSLog(@"Response is \"%@\"", response);


The problem is that you're trying to lookup the value for the key in the keys array, not in the args dictionary. Try something like this instead:

for (NSString *key in args) {
        NSLog(@"Adding to args key: %@", key);
    [request setPostValue:[args objectForKey:key] forKey:key];
}

Note this also uses fast enumeration rather than explicit (slow) enumeration.


I can see that your method signature is wrong and I have no idea how does that code compile.

- (NSString *) httpPostStringResponseUrl:(NSURL *)url:(NSDictionary *)args

the above line is broken. This should be correct:

- (NSString *) httpPostStringResponseUrl:(NSURL *)url params:(NSDictionary *)args

The call should also be something like this:

NSString *response = [web httpPostStringResponseUrl:url params:params];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜