How to save id variable using objc_getAssociatedObject / objc_setAssociatedObject?

I am using a category and some variable stored in a UIView.

but only the id type stored, so I really don't need the id type (int, float, double, char ... etc.)

How to write 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
+5
source share
2 answers

You need to convert the float to instances of NSNumber 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);
}
+16
source

To save variables such as CGPoint, CGRector CGSize, view the class NSValueand use the appropriate method:

NSValue *value;
value = [NSValue valueWithCGPoint:point];
value = [NSValue valueWithCGRect:rect];
value = [NSValue valueWithCGSize:size];

Then convert it back through:

NSValue *value = ...;
CGPoint point = value.CGPointValue;
CGRect rect = value.CGRectValue;
CGSize size = value.CGSizeValue;

FYI:

:

objc_setAssociatedObject(self, @selector(stringTag), stringTag, OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_getAssociatedObject(self, @selector(stringTag));

kStringTagKey.

0

All Articles