Reckoner
Reckoner

Reputation: 1041

Blocks in objective C

@interface
    @property (strong) void(^myPropertyBlock)(void);
@end

@implementation
    self.myPropertyBlock = ^{[self anyMethod];};
@end

Now the compiler shows a warning regarding 'strong reference cycle' which is what it should be doing.Now if I make 'self' to weak property,it works perfectly fine because as expected,it will break the strong reference cycle.

MyViewController * __weak _self = self;

Now here is the problem:

@interface
    @property (weak) void(^myPropertyBlock)(void);
@end

@implementation
    self.myPropertyBlock = ^{[self anyMethod];};    
@end

1) If I make a block as weak property,it should break the strong reference cycle as well.But ,to my surprise, it doesn't.

I have searched the net but found nothing relevant.

Upvotes: 1

Views: 65

Answers (3)

hris.to
hris.to

Reputation: 6363

You must declare block as copy otherwise it won't be copied in the heap and when you execute it you will get nasty sigsegv error. It doesn't matter even if you set it implementation and call it on next line. So you must always define it with copy and break retain cycle as needed.

Upvotes: 1

ImWH
ImWH

Reputation: 944

Statement Block property, you first need to use the copy modifier, because only after Block copy will exist in the heap.

Upvotes: 0

soumya
soumya

Reputation: 3811

Block itself will keep a strong reference to any objects it references. Declare __weak pointers outside the block and then reference this pointer within the block to avoid retain cycles.

Blocks in and of themselves that create these retain cycles.The block retains self, but self doesn't retain the block. If one or the other is released, no cycle is created and everything gets deallocated as it should.

At block "execution" time, the block copies the "value of weakSelf" (which will be nil if self has been dealloc'ed in the mean time) into strongSelf which ARC then applies a retain to. Thus, for the duration of the block, the object referenced by strongSelf will remain alive, if it was alive to begin with. If you had only relied on weakSelf, it could go nil at any time during the execution of the block.

Hope this helps you: Breaking retain cycle with strong/weak self

Upvotes: 0

Related Questions