The Retain'ed block property does not copy the copy-use copy attribute instead

I come from a heavy JavaScript-oriented background, and I switch to Objective-C as best I can. Naturally, I always came across the ability to use closing functions in my source code, for example:

@property (nonatomic, retain) void (^zoomCallback)(NSInteger width, NSInteger height, NSString *url); 

However, every time I write this to Xcode, it warns me:

The stored property of the block does not copy the copy-use copy attribute instead

I realized that you no longer need to save things manually in Objective-C due to ARC, so I admittedly rather threw this warning. I assume the block refers to my closure function, so as far as I can interpret it, I am informed that the assignment to this variable is:

 myObject.zoomCallback = someMethod; 

Some method can also be saved, and therefore the owner of someMethod will continue to exist? Did I understand correctly?

What are the negative consequences of this? If I "copy" a block, do not let the owner of someMethod be destroyed, and therefore, in the closure method itself, whenever I refer to the "I", will it no longer exist? Don't I almost want to save the block if my closure method does not do something very trivial or something that does not refer to member variables or methods?

+4
source share
1 answer

Blocks must be copied before they are saved (and in some cases just before they are used, but usually this is a strange bit of code) because the blocks are created on the stack and must be moved to the heap. If the block is not copied and the context in which it was created is destroyed, then it will not always work correctly. This is the case when a block captures some external variables (instead of using only the passed parameters).

+3
source

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


All Articles