如何存储非id类型变量使用objc_getAssociatedObject / objc_setAssociatedObject? [英] How to store not id type variable use a objc_getAssociatedObject/objc_setAssociatedObject?

查看:215
本文介绍了如何存储非id类型变量使用objc_getAssociatedObject / objc_setAssociatedObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了一个类别,并且一些变量存储在UIView中。

I use a category, and some variable stored in a UIView.

但只存储了id类型,所以我真的不想要id类型(int,float,double ,char ...等等)

but only stored id type, so I really want none id type (int, float, double, char... and so on)

如何编写代码?

#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


推荐答案

您需要将浮点数转换为NSNumber实例,反之亦然:

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);
}

这篇关于如何存储非id类型变量使用objc_getAssociatedObject / objc_setAssociatedObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆