gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:35:13 25 4
gpt4 key购买 nike

我使用一个类别和一些存储在 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

最佳答案

您需要将 float 转换为 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);
}

关于iphone - 如何使用 objc_getAssociatedObject/objc_setAssociatedObject 存储非 id 类型变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7890414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com