Wrap / attachment some additional information with UIButton in Objective c
Some time many of iOS developer facing a issue that 'How wrap/attach some additional information(It may be a object, array, dictionary etc) with a UIButton. And if you want create a UIButton category it is not possible of create extra property.
So do you do that.
Here the solution there is a trick so you can create a property in UIButton category and wrap/attach any object.
Create a UIButton category and follow this pice of code in .h file and .m file
.h
.m
How to use
So do you do that.
Here the solution there is a trick so you can create a property in UIButton category and wrap/attach any object.
Create a UIButton category and follow this pice of code in .h file and .m file
.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface UIButton (Property)
@property (nonatomic, retain) NSObject *property;
@end
.m
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@implementation UIButton (Property)
static char UIB_PROPERTY_KEY;
-(void)setProperty:(NSObject *)property
{
objc_setAssociatedObject(self, &UIB_PROPERTY_KEY, property, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSObject*)property
{
return (NSObject*)objc_getAssociatedObject(self, &UIB_PROPERTY_KEY);
}
@end
How to use
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// Set Object here. I am send a string here but if you want you can set any Object in this property.
button.property = @"HELLO";
NSLog(@"Property %@", button.property);
// don't forget set nil after use it
button.property = nil;
NSLog(@"Property %@", button.property);
// Set Object here. I am send a string here but if you want you can set any Object in this property.
button.property = @"HELLO";
NSLog(@"Property %@", button.property);
// don't forget set nil after use it
button.property = nil;
NSLog(@"Property %@", button.property);
No comments:
Post a Comment