I have a very simple class (currently used as a testing class), which uses delegate/protocol methods to interface with it's parent class. However, I would really like to convert this to use blocks. Yet I can't find a good resource or tutorial out there to help me figure out how to do this. All the blocks tutorials are just way to complicated, and I would really just like a small, concise example of how to do this.
I currently have the class:
#import <Foundation/Foundation.h>
@protocol TestObjectDelegate <NSObject>
@optional
-(void)testObjectSucceeded:(BOOL)passedTest;
-(void)testObjectedFailed:(NSError *)error;
@end
@interface TestObject : NSObject {
id<TestObjectDelegate> _delegate;
}
-(void)compare:(NSString *)stringA with:(NSString *)stringB;
@end
#import "TestObject.h"
@implementation TestObject
- (id)initWithDelegateController:(id<TestObjectDelegate>)delegate {
self = [super init];
if (self) {
_delegate = delegate;
}
return self;
}
-(void)compare:(NSString *)stringA with:(NSString *)stringB {
if ([stringA isEqualToString:stringB]) {
if(_delegate && [_delegate respondsToSelector:@selector(testObjectSucceeded:)]) {
[_delegate testObjectSucceeded:YES];
}
else {
[_delegate testObjectSucceeded:NO];
}
}
else {
if(_delegate && [_delegate respondsToSelector:@selector(testObjectedFailed:)]) {
[_delegate testObjectedFailed:nil];
}
}
}
@end
How could I begin to convert this to a blocks based function? Also, I know 'retain cycles' are something to watch out for when implementing a blocks function. What would I need to watch out for when converting this class to use blocks instead of delegate/protocols? Googling 'retain cycles' also gives some overly complicated answers.
Any starting pointers would be much appreciated?
Maybe this example gives you an idea:
typedef void (^MyCallbackBlock)(BOOL);
@interface TestObject : NSObject {
}
@property (nonatomic, copy) MyCallbackBlock myBlock;
@end
#import "TestObject.h"
@implementation TestObject
-(void) yourMethod
{
...
self.myBlock(YES); // call block with argument
...
}
- (void)dealloc
{
[myBlock release];
myBlock = nil;
[super dealloc];
}
@end
When using the object you can then define the block like this:
TestObject* theTestObject = [[TestObject alloc] init];
theTestObject.myBlock = ^(BOOL theParameter){
NSLog(@"foo");
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With