objc_setAssociatedObject function error in 64bit mode not in 32bit

后端 未结 3 1129
既然无缘
既然无缘 2020-12-15 11:48

I am using a neat table view controller called SKSTableView in my project which allows each table row to have a number of sub rows. This code works perfectly in 32

3条回答
  •  不知归路
    2020-12-15 12:25

    I came across this as well but in a different scenario where I was needing to add a property to a tagged pointer type.

    Here is what I came up with; it makes use of NSMapTable weakToStrongObjectsMapTable. It can even be used as a drop-in replacement for objc_setAssociatedObject/objc_getAssociatedObject for tagged pointers and regular object types:

    static NSString* SomeVariableKey = @"SomeVariableKey";
    
    @interface NSObject (SomeAddition)
    
    - (void)setSomeVariable:(NSObject*)var {
        [[APObjectAssociationManager defaultManager] setValue:var forKey:SomeVariableKey forAssociatedObject:self];
    }
    
    - (NSObject*)someVariable {
        return [[APObjectAssociationManager defaultManager] valueForKey:SomeVariableKey forAssociatedObject:self];
    }
    
    @end
    
    
    @interface APObjectAssociationManager ()
    
    @property (nonatomic, strong) NSMapTable *associations;
    
    @end
    
    @implementation APObjectAssociationManager
    
    
    - (id)init {
        self = [super init];
    
        if (self) {
            self.associations = [NSMapTable weakToStrongObjectsMapTable];
        }
    
        return self;
    }
    
    + (APObjectAssociationManager*)defaultManager {
        static APObjectAssociationManager *instance = nil;
    
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[APObjectAssociationManager alloc] init];
        });
    
        return instance;
    }
    
    - (void)setValue:(id)value forKey:(NSString *)key forAssociatedObject:(NSObject*)associatedObject {
    
    
        NSMutableDictionary *dictionary = [self.associations objectForKey:associatedObject];
    
        if (!dictionary) {
            dictionary = [NSMutableDictionary dictionary];
            [self.associations setObject:dictionary forKey:associatedObject];
        }
    
        [dictionary setValue:value forKey:key];
    }
    
    - (id)valueForKey:(NSString *)key forAssociatedObject:(NSObject*)associatedObject {
    
        NSDictionary *dictionary = [self.associations objectForKey:associatedObject];
        return dictionary[key];
    }
    
    @end
    

提交回复
热议问题