I've created a class which is a wrapper around NSURLConnection and users of the class pass blocks that get invoked at various stages of the connection. THe wrapper class is shown below, abbreviated for brevity:
typedef void (^ConnectionFinishedWithErrorBlock)(NSError* error);
@interface MYHTTPConnection : NSObject <NSURLConnectionDelegate>
@property (copy, nonatomic) ConnectionFinishedWithErrorBlock theErrorBlock;
@property (strong, nonatomic) NSURLConnection *connection;
- (void) establishConnectionForURL:(NSURL*) url
andConnectionFinishedWithErrorBlock: (ConnectionFinishedWithErrorBlock) errorBlock;
@end
So far I've been using it with the blocks declared inline i.e.
[self.httpConnection establishConnectionForURL: url
andConnectionFinishedWithErrorBlock:^(NSError* error)
{
...
}];
But now I have a situation where I have a very long error handling block, and to place all its code inline will get messy (as the API takes other blocks not shown here).
I know I could do something like this:
void (^httpConnectionFinishedWithError)(NSError*) =
^(NSError* error)
{
}
Then pass httpConnectionFinishedWithError to establishConnectionForURL. But httpConnectionFinishedWithError contains calls to self. The calls to self are fine when the block is declared inline, but not when done as above as obviously this generates compilation errors.
So I was wondering if/how the block could be made a block property of the calling class? (I've already used blocks as properties of classes before, as is done in the MYHTTPConnection class above which works fine, but in this situation I can't get the syntax right to add the block that is passed to establishConnectionForURL as a property of the calling class).
Alternatively the httpConnectionFinishedWithError could just call another function, but in that situation I'd have to pass self as a parameter, how would I obtain self within the block in this case?
Are there other more elegant solutions?
Many thanks
EDIT: Updated to show example of compilation error
void (^httpConnectionFinishedWithError)(NSError*) =
^(NSError* error)
{
self.boolProperty = NO; // here
}
selfpointer inside any ObjC method. If you're in a class method,selfpoints to the class rather than an instance -- is that the problem? - jscs