0

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}}?

KingPolygon
  • 4,753
  • 7
  • 43
  • 72
  • objc_getAssociatedObject(self, @selector(tapArea)) is probably returning an NSString since that error says you're attempting to perform CGRectValue on an NSString. I'd recommend also posting your objc_getAssociatedObject method for a more thorough answer. – Lyndsey Scott Feb 08 '15 at 09:42
  • I figured that much, except I've tried using ```CGRectFromString()```, but can't seem to get it working, without it throwing an inline error. – KingPolygon Feb 08 '15 at 09:44
  • @LyndseyScott objc_getAssociatedObject is a runtime method :) – kovpas Feb 08 '15 at 09:57
  • OK, I'll find it in the docs then. – Lyndsey Scott Feb 08 '15 at 09:57

1 Answers1

3

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

ozz
  • 1,137
  • 7
  • 9
  • Perfect explanation. Thanks for the tips. You're right at this point (seeing that I have a few categories on UIButton), it might be best to just subclass it. With that said ```OBJC_ASSOCIATION_RETAIN_NONATOMIC``` worked perfectly. :D – KingPolygon Feb 08 '15 at 10:02
  • you shouldn't subclass UIButton: http://stackoverflow.com/questions/13202161/why-shouldnt-i-subclass-a-uibutton – Tyler Jun 23 '16 at 16:33