1

I'm looking to add a .owner and .number method to the UIButton class. I need to assign each individual number an (int)number so that I can use numbers to separate the buttons.

e.g so I could write buttonName.number = 1 and buttonName.owner = @"Player1";

How can I go about doing this?

1 Answer 1

2

There are few ways to do this thing. The easier one is to subclass the UIButton class and add the properties as you needed which could be achieved as;

@interface MyButton:UIButton
@property(nonatomic, assign) int number;
@property(nonatomic, strong) NSString *owner
@end

And the other way is to use runtime to add properties into the class. For this you would create a category for the class and then add property into the interface and then add properties to it using the runtime as;

@interface UIButton(MyCategory)
@property(nonatomic, assign) float number;
@property(nonatomic, strong) NSString *owner;
@end

@implementation UIButton(MYCategory)
NSString *const numberKey = @"kNumberKey";
NSString *const ownerKey = @"kOwnerKey";

 - (float)number{ 
    return [objc_getAssociatedObject(self, &numberKey) floatValue]; 
 } 

-(void)setNumber:(float)num{ 
  objc_setAssociatedObject(self, &numberKey,[NSNumber numberWithFloat:num], OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
}

-(NSString*)owner{
    return objc_getAssociatedObject(self, &ownerKey);
}

-(void)setOwner:(NSString *)own{
    objc_setAssociatedObject(self, &ownerKey, own, OBJC_ASSOCIATION_COPY);
}

@end

With this you will be able to add the custom properties to the UIButton class itself.

Sign up to request clarification or add additional context in comments.

6 Comments

I made a category called UIButton and its a category of UIButton. I put the interface and implementation in there and get use of undeclared identifier 'number' and 'owner'
Make sure you have made correct imports for this. Use #import <objc/runtime.h>. Sorry I have missed something here. See my edits.
Well see it now. It should work. I was making some mistake myself instead of using the key and the value passed in methods, I was using something else.
Sorry, I was not checking the error in the code. But the edited code above is working implementation.
Thank you, it works but I'm having some problems with the number. Getting a conflicting return and parameter types for 'number' - 'int' vs 'NSNumber'. Compiles fine but when the button loads the program crashes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.