问题
Example:
typedef void(^responseBlock)(NSDictionary*, NSError *); @interface MyClass : NSObject { [??] responseBlock responseHandler; }
What qualifier should I put in the [??] brackets?
I've read that blocks as properties should be setup with the copy qualifier...but in this case I don't need the block exposed as a property. I simply want it to remain an ivar but how can I specify copy? And also, without specifying anything what is the default qualifier used? Is it __strong as in the case with everything else?
I'm using ARC on ios5.
回答1:
Yes, Blocks are objects in ObjC, so __strong
is the appropriate qualifier. Since that's the default, you can in fact leave it off.
There's no way for you to specify that the Block be copied on assignment without a property -- that will be your responsibility (responseHandler = [someBlock copy];
). You could declare a property that's only visible to this class itself (not available to other code) by putting a class extension in your .m file:
@interface MyClass ()
@property (copy) responseBlock responseHandler;
@end
This (upon being synthesized) will give you the usual accessor methods, which will take care of the copy for you when you use them.
Also be aware that it's possible (and now the recommended procedure) to declare instance variables in the @implementation
block. It sounds like you want this to be a private attribute (no property access), and the ivars declared there can't be seen by any other code. (Of course you don't need to do this if you're using a property; @synthesize
will create the ivar for you.)
@implementation MyClass
{
responseBlock responseHandler;
}
// Continue with implementation as usual
来源:https://stackoverflow.com/questions/10128552/what-qualifier-should-i-use-to-declare-a-block-as-an-ivar