ARC: EXC_BAD_ACCESS when calling a method from inside a block, inside a delegate method

I created a block inside the delegate method, and I use it to call a static method in another class. I get an EXC_BAD_ACCESS error even if I have NSZombies enabled. There are some reports of similar issues here - I think this is the closest:

ARC: getting EXC_BAD_ACCESS from the inner block used in the delegate method

But so far I have not found anything that helped. Here is the code:

@interface MyClass() @property (nonatomic, copy) CaseBlock c; @end .... //NSURLConnection delegate method - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys: //blows up after executing this ^() { [AnotherClass staticMethod]; },authURL, ^() { NSLog(@"TODO");}, searchURL, ^() { NSLog(@"TODO"); }, itemURL, nil]; self.c = [[d objectForKey:[self.url path]] copy]; if (self.c) { self.c(); } else { NSLog(@"WARN unexpected response path"); } } 

This is the first time that I have tried to use blocks, but I can say that this causes a problem, because calling the method from outside the block works fine. And also, as far as I can tell, all the code I wrote is actually executing, AND THEN the EXC_BAD_ACCESS error occurs. But, I am new to Objective-C, so please correct me if I am wrong about this.

+4
source share
1 answer

You need to copy the blocks if they need to survive the area in which they were created. Since dictionaryWithObjectsAndKeys: deals with objects in general, and not with specific blocks, it does not know to copy them, so you have to copy them to them.

 NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys: //blows up after executing this [^() { [AnotherClass staticMethod]; } copy], authURL, [^() { NSLog(@"TODO");} copy], searchURL, [^() { NSLog(@"TODO"); } copy], itemURL, nil]; 
+9
source

Source: https://habr.com/ru/post/948860/


All Articles