如何存储非id类型变量使用objc_getAssociatedObject / objc_setAssociatedObject?

时间:2011-10-25 13:58:02

标签: iphone objective-c

我使用了一个类别,以及一些存储在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

2 个答案:

答案 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)

要存储CGPointCGRectCGSize等变量,请查看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变量。