前言
我们都知道 category 可以为某个类来添加方法,但是是否可以添加属性呢?如何添加?
category 分析
category 可以为我们重写类的方法,但是我们如果通过他来添加属性,会发生什么
首先,我们创建了一个 Person 类。当前此类只有一个属性 name,而当我们声明一个属性的时候,实际上是生成了一个成员变量和它的 set get 方法,这样我们在使用的时候才能正常的拿到对应的值。
image.png那么当我们在 category 里声明这个属性的时候,能否同样给我们生成这些内容呢?
我们创建一个 Person 的 category 并为它添加一个属性 age , 然后我们来为这个 age 赋值。
image.png image.png可以发现我们的程序崩溃了,崩溃堆栈信息如下:
2021-09-14 16:40:31.808475+0800 CategroyTest[40231:1531935] Hello, World!
2021-09-14 16:40:31.811430+0800 CategroyTest[40231:1531935] -[Person setAge:]: unrecognized selector sent to instance 0x10063cc60
2021-09-14 16:40:31.814593+0800 CategroyTest[40231:1531935] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Person setAge:]: unrecognized selector sent to instance 0x10063cc60'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff2066a83b __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007fff203a2d92 objc_exception_throw + 48
2 CoreFoundation 0x00007fff206ed34d -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x00007fff205d28cb ___forwarding___ + 1448
4 CoreFoundation 0x00007fff205d2298 _CF_forwarding_prep_0 + 120
5 CategroyTest 0x0000000100003e7c main + 92
6 libdyld.dylib 0x00007fff20512f3d start + 1
)
libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Person setAge:]: unrecognized selector sent to instance 0x10063cc60'
terminating with uncaught exception of type NSException
使用 .age 时崩溃如下
2021-09-14 16:44:33.699452+0800 CategroyTest[40267:1535013] Hello, World!
2021-09-14 16:44:33.699984+0800 CategroyTest[40267:1535013] -[Person age]: unrecognized selector sent to instance 0x10482c1c0
2021-09-14 16:44:33.700674+0800 CategroyTest[40267:1535013] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Person age]: unrecognized selector sent to instance 0x10482c1c0'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff2066a83b __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007fff203a2d92 objc_exception_throw + 48
2 CoreFoundation 0x00007fff206ed34d -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x00007fff205d28cb ___forwarding___ + 1448
4 CoreFoundation 0x00007fff205d2298 _CF_forwarding_prep_0 + 120
5 CategroyTest 0x0000000100003e77 main + 87
6 libdyld.dylib 0x00007fff20512f3d start + 1
)
libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Person age]: unrecognized selector sent to instance 0x10482c1c0'
terminating with uncaught exception of type NSException
通过堆栈信息我们可以发现,我们虽然可以使用这个属性,但实际上这个属性并没有生成对应的 set get 方法, 所以会产生崩溃。
如何正确的给类添加属性
这个时候我们就需要使用到 runtime api 为我们提供的一套机制
/**
* Sets an associated value for a given object using a given key and association policy.
*
* @param object The source object for the association.
* @param key The key for the association.
* @param value The value to associate with the key key for object. Pass nil to clear an existing association.
* @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
*
* @see objc_setAssociatedObject
* @see objc_removeAssociatedObjects
*/
OBJC_EXPORT void
objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
id _Nullable value, objc_AssociationPolicy policy)
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
/**
* Returns the value associated with a given object for a given key.
*
* @param object The source object for the association.
* @param key The key for the association.
*
* @return The value associated with the key \e key for \e object.
*
* @see objc_setAssociatedObject
*/
OBJC_EXPORT id _Nullable
objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
/**
* Removes all associations for a given object.
*
* @param object An object that maintains associated objects.
*
* @note The main purpose of this function is to make it easy to return an object
* to a "pristine state”. You should not use this function for general removal of
* associations from objects, since it also removes associations that other clients
* may have added to the object. Typically you should use \c objc_setAssociatedObject
* with a nil value to clear an association.
*
* @see objc_setAssociatedObject
* @see objc_getAssociatedObject
*/
OBJC_EXPORT void
objc_removeAssociatedObjects(id _Nonnull object)
OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0, 2.0);
objc_setAssociatedObject
objc_setAssociatedObject(<#id _Nonnull object#>, <#const void * _Nonnull key#>, <#id _Nullable value#>, <#objc_AssociationPolicy policy#>)
这个方法是添加关联对象。
参数一:指我们为谁来添加关联对象,因为我们是在 category 中写的,是为 person 添加对象,所以此处直接写 self 即可。
参数二:指的是我们存储值得时候对应的 Key 是什么,当我们需要添加多个属性时,需要用 key 来做区分,所以我们要保证 key 值唯一,这样添加多个属性才能区分我们取得的哪个属性的值。我们可以通过定义变量取其地址来定义
static const void* kAge = &kAge;
或者
static const char kAge; // 使用的时候直接使用 &kAge, char 相比地址更节省内存。
参数三:指的是我们需要关联的值是哪个?当前我们为 age 添加,所以此处写 age 即可,此处需要使用对象,所以我们使用 @(age);
参数四:指的是关联策略,其实就是我们对象写属性时的内存管理策略,此处我们用 OBJC_ASSOCIATION_ASSIGN
typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
OBJC_ASSOCIATION_ASSIGN = 0, /**< Specifies a weak reference to the associated object. */
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.
* The association is not made atomically. */
OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied.
* The association is not made atomically. */
OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object.
* The association is made atomically. */
OBJC_ASSOCIATION_COPY = 01403 /**< Specifies that the associated object is copied.
* The association is made atomically. */
};
完整代码如下:
Person+Test.h
#import "Person.h"
NS_ASSUME_NONNULL_BEGIN
@interface Person (Test)
@property (nonatomic,assign) int age;
@end
NS_ASSUME_NONNULL_END
Person+Test.m
#import "Person+Test.h"
#import <objc/runtime.h>
const void* kAge = &kAge;
@implementation Person (Test)
- (void)setAge:(int)age{
objc_setAssociatedObject(self, kAge, @(age), OBJC_ASSOCIATION_ASSIGN);
}
- (int)age{
return [objc_getAssociatedObject(self, kAge) intValue];
}
@end
这个时候可以看出我们已经可以正常运行了
image.png原理解读
Q:通过 category 存储的内容是否会存储到原有对象的数据结构中?如果存储的?
A:不会影响原来结构
通过查看 runtime 源码可以发现,重要的类和数据结构有下面几个
AssociationsManager
AssocaitionsHashMap
AssociationsMap
ObjectAssociation
通过 AssociationsManager 来管理 AssocaitionsHashMap,
而 AssocaitionsHashMap 中则以 object 为 key,AssociationsMap 为 Value,
AssociationsMap 则以我们传入的 key 为 key, ObjectAssociation 为 value,
ObjectAssociation 中则存储了我们传入的 value 和内存管理规则。
其他
objc_removeAssociatedObjects 会移除所有关联对象,如果只需要单独移除某个只要在 objc_setAssociatedObject 时 value 为 nil 即可。
网友评论