Search code examples
iosobjective-cafnetworking-2

Unable to save AFNetworking responseObject


one property:

@property (strong, nonatomic)NSDictionary *responseDict;

The method:

- (void)sendRequestDictionay:(NSDictionary *)dict ToServerWithMode:(NSInteger)mode {
    NSString *requestString = [self requestStringwithMode:mode];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [manager POST:requestString parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            self.responseDict = responseObject;
            NSLog(@"JSON: %@", self.responseDict);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        self.responseDict = nil;
        NSLog(@"%@", error);
    }];
    NSLog(@"response dictionary is nil or not: %@", self.responseDict);   
}

Every time the first NSLog() will log the JSON, but the third NSLog just log :

"response dictionary is nil or not: (null)"

It seems the responseObject never assigned to self.responseDict. It is contradict with the first NSLog.

So another method in another class which take self.responseDict as a parameter will not work.


Solution

  • Your question is a similar problem to Returning method object from inside block

    The block runs asynchronously so it will run after the log statement. You should put the log (indeed you already have a log so you should see it), and the code which uses the result, inside the block (or in a method which is called from the block).