Search code examples
iosobjective-cuibuttoncgrectassociated-object

Creating a CGRect as an Associated Object?


I'm attempting to create a CGRect property for my UIButton's as an associated object, so that I don't have to subclass UIButton just for this.

Basically I'm adding a property titled, tapArea, and I'm having trouble creating it. This is what I have so far:

@dynamic tapArea;

- (void)setTapArea:(CGRect)tapArea {
    objc_setAssociatedObject(self, @selector(tapArea), [NSValue valueWithCGRect:tapArea], OBJC_ASSOCIATION_ASSIGN);
}

- (CGRect)tapArea {
    return [objc_getAssociatedObject(self, @selector(tapArea)) CGRectValue];
}

When I NSLog say dogButton.tapArea, the logger prints out {{0,0},{0,0}} which makes sense. The problem arises when I attempt to set it. I get the following crash:

-[__NSCFString CGRectValue]: unrecognized selector sent to instance 0x14e65e80

I believe I'm getting this error bc I'm using NSValue, but I'm not pulling it back out correctly. How can I fix my getter?

P.S. This is how I'm declaring my property in my category header file:

@property (nonatomic, assign) CGRect tapArea;

Also, how can I set my property equal to the button's frame by default instead of {{0, 0}, {0, 0}}?


Solution

  • You're working awfully hard to avoid subclassing a UIButton, which is pretty damn easy and quick. Don't make it more complicated than necessary.

    Also, an NSValue is an NSObject which should be retained not assigned. Your storage semantic is incorrect, which is probably why you are having problems. Your associated object is an object and needs to be retained like an object.

    Use OBJC_ASSOCIATION_RETAIN_NONATOMIC