Category添加weak属性的精简版本

网上有很多版本,我提供一种不用加新类就可以实现的方法。

创建NSObject的Category

NSObject+Ext.h

#import <Foundation/Foundation.h>
typedef void (^DeallocBlock)();

@interface NSObject (Ext)
@property (nonatomic, weak) id weakObj;
@property (nonatomic, copy) DeallocBlock block;
@end

NSObject+Ext.m

#import "NSObject+Ext.h"
#import <objc/runtime.h>

static NSString *WEAK_KEY = @"weakObj";
static NSString *BLOCK_KEY = @"block";

@implementation NSObject (Ext)
- (id)weakObj {
    return objc_getAssociatedObject(self, &WEAK_KEY);
}

- (void)setWeakObj:(id)weakObj {
    [weakObj setBlock:^() {
        objc_setAssociatedObject(self, &WEAK_KEY, nil, OBJC_ASSOCIATION_ASSIGN);
    }];
    objc_setAssociatedObject(self, &WEAK_KEY, weakObj, OBJC_ASSOCIATION_ASSIGN);
}

- (DeallocBlock)block {
    return objc_getAssociatedObject(self, &BLOCK_KEY);
}

- (void)setBlock:(DeallocBlock)block {
    objc_setAssociatedObject(self, &BLOCK_KEY, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (void)dealloc {
    self.block ? self.block() : nil;
    objc_setAssociatedObject(self, &BLOCK_KEY, nil, OBJC_ASSOCIATION_ASSIGN);
}
#pragma clang diagnostic pop
@end

测试用法

NSObject *obj1 = [NSObject new];
NSObject *obj2 = [NSObject new];
obj1.weakObj = obj2;
NSLog(@"%@", obj1.weakObj);
obj2 = nil;
NSLog(@"%@", obj1.weakObj);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值