Search code examples
objective-cdelegatesobjective-c-category

Using a Delegate in a Category


I've created a category with 2 properties but I'm having an issue trying to use one as a delegate.

    //  UIView+Dropdown.h
    #import <UIKit/UIKit.h>

   @protocol DropDownAnimationDoneDelegate <NSObject>
    -(void) onDropDownAnimationDone:(id)sender;
    @end

    @interface UIView (Dropdown)
    @property (strong, nonatomic) id <DropDownAnimationDoneDelegate> delegateForDropDown;
    @property (nonatomic,assign) BOOL isDropped;

    //  UIView+Dropdown.m
    #import "UIView+Dropdown.h"
    #import <objc/runtime.h>

    @implementation UIView (Dropdown)
    -(void)setDelegateForDropDown:(id)ddDelegate{
        objc_setAssociatedObject(self, @selector(delegateForDropDown),ddDelegate,OBJC_ASSOCIATION_RETAIN_NONATOMIC);}

    -(id)delegateForDropDown{
        return objc_getAssociatedObject(self, @selector(delegateForDropDown));}

    -(void)setIsDropped:(BOOL)dropIt{
        objc_setAssociatedObject(self, @selector(isDropped), [NSNumber numberWithBool:dropIt], OBJC_ASSOCIATION_RETAIN_NONATOMIC);}

    -(BOOL)isDropped{
        return [objc_getAssociatedObject(self, @selector(isDropped)) boolValue];}

The delegate will be used for notification after an animation block is complete:

    [UIView animateWithDuration:0.75
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{self.center = newCenter;}
                     completion:^(BOOL finished){
                         if ([[self delegateForDropDown] respondsToSelector:@selector(onDropDownAnimationDone:)])
                         [[self delegateForDropDown] onDropDownAnimationDone:self];}];

My problem is delegateForDropDown always contains nil. The boolean property works fine so I suspect it has someting to do with the delegate's type being id


Solution

  • Found the problem. Programming error on my part. I was setting the delegate property for the wrong view so the problem was in the calling class. It works fine now. TomSwift pointed me in the right direction. Thanks.