سؤال

I come from a heavy JavaScript-oriented background and I'm transitioning as best I can into Objective-C. Naturally, I always find myself jumping at the opportunity to utilize closure functions in my source code, such as:

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

However, each time I jot this into Xcode, it warns me:

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

It was my understanding that you no longer have to retain things manually anymore in Objective-C due to ARC, so I'm admittedly rather thrown by this warning. I'm assuming by block it's referring to my closure function, so as far as I can interpret it's telling me that assigning this variable:

myObject.zoomCallback = someMethod;

Would also cause someMethod to be retained, and thus the owner of someMethod to continue to exist? Did I get that right?

What are the negative repercussions of this? If I "copy" the block, wont it allow for the owner of someMethod to be destroyed, and thus within the closure method itself any time I refer to "self" it will no longer exist? Don't I almost always want to retain the block unless my closure method is doing something very trivial or something that doesn't reference member variables or methods?

هل كانت مفيدة؟

المحلول

Blocks need to be copied before they are stored (and in some cases just before you use them, but that's usually a strange bit of code) because blocks are created on the stack and need to be moved to the heap. If the block isn't copied and the context in which it was created is destroyed then it won't always work properly. This is the case when the block captures some external variables (instead of only using the passed parameters).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top