Is there any alternative to use like tag
to property of UIView? The thing is I'd like to pass UITextField
some NSInteger
. Way to do is tag
. But I want to pass 2 different NSInteger
.
Any ideas?
You could subclass UITextField and add two NSInteger properties to the class.
@interface CustomTextField : UITextField
@property (nonatomic, assign) NSInteger x;
@property (nonatomic, assign) NSInteger y;
@end
You can attach any data to any object using an Associative Reference. This is a very handy approach. It even correctly handles memory management. I sometimes use a category to wrap these so I can create new properties on an existing class. For example, in one project I'd like every view controller to know about a special label (like how they all know about navigationController
). I do it this way:
@interface UIViewController (MYSpecialViewController)
@property (nonatomic, readwrite, strong) UILabel *specialLabel;
@end
@implementation UIViewController (MYSpecialViewController)
static const char kMySpecialLabelKey;
- (UILabel *)specialLabel
{
return objc_getAssociatedObject(self, &kMySpecialLabelKey);
}
- (void)setSpecialabel:(UILabel *)value
{
objc_setAssociatedObject(self, &kMySpecialLabelKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
You can find a simple working example using a UIAlertView
in the iOS5:PTL sample code for Chapter 3.
id
, so pass one. Just wrap the integer in an NSNumber - Rob Napier 2012-04-05 02:33
Take the general, object-oriented solution, but remember you can a stuff lot of data into a tag:
- (uint32_t)pack:(uint16_t)a with:(uint16_t)b {
return (uint32_t)(a << 16 | b);
}
- (uint16_t)getA:(uint32_t)pair {
return (uint16_t)((pair & 0xffff0000) >> 16);
}
- (uint16_t)getB:(uint32_t)pair {
return (uint16_t)(pair & 0xffff);
}
// use it
- (void)setupSomeView {
someView.tag = [self pack:1024 with:2048];
}
- (IBAction)someControlEventHappened:(id)sender {
NSLog(@"%d %d", [self getA:sender.tag], [self getB:sender.tag]);
}
Caveats: