1

I'm developing an iOS 5.0+ app and I'm creating a Category for an UIButton:

@interface UIButton (NotificationBall)

@property (nonatomic, assign) NSInteger type;
@property (nonatomic, assign) NSInteger index;

@end

And its implementation:

#import "UIButton+NotificationBall.h"

@implementation UIButton (NotificationBall)

@dynamic type;
@dynamic index;

@end

Searching on internet I've found this question, but I haven't found any examples with NSInteger.

Do I need to use NSNumber instead of NSInteger?
If I use, NSNumber, what do I have to do?

Community
  • 1
  • 1
VansFannel
  • 45,055
  • 107
  • 359
  • 626

1 Answers1

3

Only Objective-C objects can be set as associated objects, scalars cannot be used directly. So you could declare the property as

@property (nonatomic, strong) NSNumber *type;

and directly use the code from the answer https://stackoverflow.com/a/5500525/1187415 that you referenced to.

Or you keep the NSInteger property, and wrap/unwrap it to NSNumber in the getter/setter method like this:

-(void)setType:(NSInteger)type
{
    objc_setAssociatedObject(self, &UIB_TYPE_KEY, @(type), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSInteger)type
{
    return [objc_getAssociatedObject(self, &UIB_TYPE_KEY) integerValue];
}

Remark: "type" and "index" are quite common names. You should consider prepending the property names with some prefix, to avoid a possible name collision with existing properties of UIButton.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382