Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store not id type variable use a objc_getAssociatedObject/objc_setAssociatedObject?

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

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

How to write a 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
like image 803
bitmapdata.com Avatar asked Oct 25 '11 13:10

bitmapdata.com


People also ask

When to use objc_ setassociatedobject?

Sets an associated value for a given object using a given key and association policy.

What is Objc_setassociatedobject?

objc_getAssociatedObject. Returns the value associated with a given object for a given key. You can find the documentation in this Apple web page. This method wants two parameters: object: Any! : The source object for the association.


2 Answers

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);
}
like image 92
Robin Summerhill Avatar answered Oct 19 '22 22:10

Robin Summerhill


To store variables such as CGPoint, CGRect or CGSize, have a look at NSValue class and use appropriate method:

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

Then convert it back via:

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

FYI:

A much faster way of setting and getting associated objects could be this:

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

This way you don't have to create the kStringTagKey variable.

like image 32
OlDor Avatar answered Oct 19 '22 23:10

OlDor