Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to replace delegate with block using ARC
    primarykey
    data
    text
    <p>I can replace delegate with block using this method: <a href="https://stackoverflow.com/questions/8646476/best-technique-for-replacing-delegate-methods-with-blocks">Best Technique for Replacing Delegate Methods with Blocks</a></p> <p>I use this method to replace delegate:</p> <pre><code>// Generic Block Delegate @interface __DelegateBlock:NSObject typedef void (^HeapBlock)(NSInteger); @property (nonatomic, copy) HeapBlock callbackBlock; @end @implementation __DelegateBlock @synthesize callbackBlock; - (id) initWithBlock:(void(^)(NSInteger))callback { // Init and copy Callback Block to the heap (@see accessor) if (self = [super init]) [self setCallbackBlock:callback]; return [self autorelease]; } - (void) dealloc { // Release the block [callbackBlock release], callbackBlock = nil; [super dealloc]; } - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { // Return the result to the callback callbackBlock(buttonIndex); // Detach the block delegate, will decrement retain count SEL key = @selector(alertWithTitle:message:clickedBlock:cancelButtonTitle:otherButtonTitles:); objc_setAssociatedObject(alertView, key, nil, OBJC_ASSOCIATION_RETAIN); key = nil; // Release the Alert [alertView release]; } @end @implementation UIAlertView (BlocksDelegate) + (id) alertWithTitle:(NSString*)title message:(NSString*)message clickedBlock:(void(^)(NSInteger))buttonIndexClickedBlock cancelButtonTitle:(NSString*)cancelButtonTitle otherButtonTitles:(NSString*)otherButtonTitles { // Create class to hold delegatee and copy block to heap DelegateBlock *delegatee = [[__DelegateBlock alloc] initWithBlock:buttonIndexClickedBlock]; [[delegatee retain] autorelease]; // Create delegater UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:delegatee cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil]; // Attach the Delegate Block class to the Alert View, increase the retain count objc_setAssociatedObject(alert, _cmd, delegatee, OBJC_ASSOCIATION_RETAIN); // Display the alert [alert show]; return alert; } @end </code></pre> <p>I should retain delegate using</p> <pre><code>// Create class to hold delegatee and copy block to heap DelegateBlock *delegatee = [[__DelegateBlock alloc] initWithBlock:buttonIndexClickedBlock]; [[delegatee retain] autorelease]; </code></pre> <p>but how to do it in ARC? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload