Search code examples
objective-ciosios5ios4

is there no way to save data from block to a property or outside object in ios obj-c


I have designed a class "AsyncHttpRequest" for asynchronous http request handling and the class initializer takes a block as a parameter.

The block is called from "AsyncHttpRequest" classes's following delegate implementation :

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

   NSDictionary *dict = [NSJSONSerialization
        JSONObjectWithData:_dataResponseData //1
                   options:kNilOptions
                     error:&error];

   myBlock(dict); 

}

and I am creating instance of the above class from a view controller like the following

- (void)viewDidLoad {
    [super viewDidLoad];
__block NSDictionary *myDic; 

AsyncHttpRequest *r = [[AsyncHttpRequest alloc] initWithUrl:urlStr withBlock:^(NSDictionary *d){

        NSLog(@"List = %@",d);  //Its working
        NSDictionary *locDic = [[NSDictionary alloc] initWithDictionary:d]; 
         // the above is working

        myDic = d; //not working

        myDic = [[NSDictionary alloc] initWithDictionary:locDic]; 
            // The above code is not working..   
     }];
}

It is giving the following error : error: address doesn't contain a section that points to a section in a object file

is there no way to save data from block to a property or outside object in obj-c?

Thank you....I have been trying this for last 3 hours and not getting any solution.

Thanks


Solution

  • I think it's possible that the myDic is being deallocated before it's being used.

    Here's my reasoning, -[AsyncHttpRequest initWithUrl:withBlock:] captures the block, but myDic is not retained. At some point in the future, the connectionDidFinishLoading method is called, but by then the myDic variable is now out of scope as it's been deallocated.

    Makes sense?

    If this is the case, then possible solutions may include:

    • retain myDic before passing it to the -[AsyncHttpRequest initWithUrl:withBlock:] method. Note: myDic should be an instance variable/
    • create a NSDictionary property on AsyncHttpRequest and set the property to myDic.