I use a category, and some variable stored in a UIView.
but only stored id type, so I really want none id type (int, float, double, char... and so on)
How to write a code?
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@interface UIView (CountClip)
@property (nonatomic, copy) NSString *stringTag;
@property (nonatomic) float offsetY;
@end
#import "UIView+CountClip.h"
@implementation UIView (CountClip)
static NSString *kStringTagKey = @"StringTagKey";
- (NSString *)stringTag
{
return (NSString *)objc_getAssociatedObject(self, kStringTagKey);
}
- (void)setStringTag:(NSString *)stringTag
{
objc_setAssociatedObject(self, kStringTagKey, stringTag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (float)offsetY
{
// how to write a correct code?
return objc_getAssociatedObject(self, <#what is a code?#>);
}
- (void)setOffsetY:(float)offsetY
{
// how to write a correct code?
objc_setAssociatedObject(self, <#what is a code?#>,...);
}
@end
Sets an associated value for a given object using a given key and association policy.
objc_getAssociatedObject. Returns the value associated with a given object for a given key. You can find the documentation in this Apple web page. This method wants two parameters: object: Any! : The source object for the association.
You need to convert floats to NSNumber instances and vice versa:
static NSString *kOffsetYTagKey = @"OffsetYTagKey";
- (float)offsetY
{
// Retrieve NSNumber object associated with self and convert to float value
return [objc_getAssociatedObject(self, kOffsetYTagKey) floatValue];
}
- (void)setOffsetY:(float)offsetY
{
// Convert float value to NSNumber object and associate with self
objc_setAssociatedObject(self, kOffsetYTagKey, [NSNumber numberWithFloat:offsetY], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
To store variables such as CGPoint
, CGRect
or CGSize
, have a look at NSValue
class and use appropriate method:
NSValue *value;
value = [NSValue valueWithCGPoint:point];
value = [NSValue valueWithCGRect:rect];
value = [NSValue valueWithCGSize:size];
Then convert it back via:
NSValue *value = ...;
CGPoint point = value.CGPointValue;
CGRect rect = value.CGRectValue;
CGSize size = value.CGSizeValue;
FYI:
A much faster way of setting and getting associated objects could be this:
objc_setAssociatedObject(self, @selector(stringTag), stringTag, OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_getAssociatedObject(self, @selector(stringTag));
This way you don't have to create the kStringTagKey
variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With