문제

I have been trying to use objective c blocks for the first time because I have really enjoyed using closures in languages such as Python and Haskell.

I have run into a problem however that I am hoping someone might be able to help with.

Below is a simplest version of the problem I am having.

typedef void(^BlockType)(NSString *string);

- (void)testWithtarget:(id)target action:(SEL)action
{
    BlockType block = ^(NSString *string) {
        [target performSelector:action withObject:data];
    };

    block(@"Test String"); // Succeeds

    [self performSelector:@selector(doBlock:) withObject:block afterDelay:5.0f];
}

- (void)doBlock:(BlockType)block
{
    block(@"Test String 2"); // Causes EXC_BAD_ACCESS crash
}

So it appears to be some sort of memory management issue which doesn't suprise me but I just don't have the knowledge to see the solution. Possibly what I am trying may not even be possible.

Interested to see what other people think :)

도움이 되었습니까?

해결책

The block is not retained, since it is only present on the stack. You need to copy it if you want to use it outside the scope of the current stack (i.e. because you're using afterDelay:).

- (void)testWithtarget:(id)target action:(SEL)action
{
    BlockType block = ^(NSString *string) {
        [target performSelector:action withObject:data];
    };

    block(@"Test String"); // Succeeds

    [self performSelector:@selector(doBlock:) withObject:[block copy] afterDelay:5.0f];
}

- (void)doBlock:(BlockType)block
{
    block(@"Test String 2");
    [block release];
}

It's a bit hap-hazard however since you're copying and releasing across method calls, but this is how you'd need to do it in this specific case.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top