我使用了一个类别,以及一些存储在UIView中的变量。
但只存储了id类型,所以我真的不想要id类型(int,float,double,char ......等等)
如何编写代码?
#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
答案 0 :(得分:17)
您需要将浮点数转换为NSNumber实例,反之亦然:
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);
}
答案 1 :(得分:1)
要存储CGPoint
,CGRect
或CGSize
等变量,请查看NSValue
类并使用适当的方法:
NSValue *value;
value = [NSValue valueWithCGPoint:point];
value = [NSValue valueWithCGRect:rect];
value = [NSValue valueWithCGSize:size];
然后通过以下方式将其转换回来:
NSValue *value = ...;
CGPoint point = value.CGPointValue;
CGRect rect = value.CGRectValue;
CGSize size = value.CGSizeValue;
<强>供参考:强>
更快的设置和获取关联对象的方法可能是:
objc_setAssociatedObject(self, @selector(stringTag), stringTag, OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_getAssociatedObject(self, @selector(stringTag));
这样您就不必创建kStringTagKey
变量。