故事背景
01 环境及场景
编译环境Xcode 12.5.1
2021年8月的某一天,Augus正在调试我的项目需要A,因为A要求须要接入一个SDK进行实现某些采集性能
02 操作流程
- 在程序启动的最开始中央,初始化SDK,并分配内存空间
- 在某次的启动中就呈现了以下谬误:
Trapped uncaught exception ‘NSGenericException’, reason: ‘* Collection <__NSSetM: 0x2829f9740> was mutated while being enumerated.’
03 初步猜想
开始的时候,我先排除本人代码的起因(毕竟代码本人写的,还是求稳一些),因为调试模式下没有开全局断点,所以本次的解体就这么被错失机会定位
为了下一次的复现
- 首先进行了NSMutableSet某些办法的hook
- 开启全局断点
04 最初定位
我的项目中引入SDK导致的解体
问题定位
01 问题起因
被引入第三方的SDK在某个逻辑中应用的NSMutableSet遍历中对原可变汇合进行同时读写的操作
复现同样解体的场景,Let’s do it
NSMutableSet *mutableSet = [NSMutableSet setWithObjects:@"1",@"2",@"3", nil];
for (NSString *item in mutableSet) {
if ([item integerValue] < 3) {
[mutableSet removeObject:item];
}
}
02 控制台日志
很好,当初曾经晓得了问题的起因,那么接下来解决问题就很容易了,让咱们持续
解决方案
01 问题起因总结
不能在一个可变汇合,包含NSMutableArray,NSMutableDictionary等相似对象遍历的同时又对该对象进行增加或者移除操作
02 解决问题
把遍历中的对象进行一次copy操作
其实其中的情理很简略,我当初简而概括
你在内存中曾经初始化一块区域,而且调配了地址,那么零碎在这次的遍历中会把这次遍历包装成原子操作,因为会可能会拜访坏内存或者越界的问题,当然这也是出于平安起因,不同的零碎下的实现形式不同,然而底层的原理是统一的,都是为了爱护对象在操作过程中不受可变因素的更新
03 那问题来了
- copy是什么?
- copy在底层如何实现?
- copy有哪些须要留神的?
原理
01 copy是什么
copy是Objective-C编程语言下的属性润饰关键词,比方润饰Block orNS*结尾的对象
02 copy如何实现
对须要实现的类恪守NSCopying协定
实现NSCopying协定,该协定只有一个办法
- (id)copyWithZone:(NSZone *)zone;
举例说明,首先咱们新建一个Perosn类进行阐明,上面是示例代码
// The person.h file
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Person : NSObject<NSCopying>
- (instancetype)initWithName:(NSString *)name;
@property(nonatomic, copy) NSString *name;
/// To update internal mutabl set for adding a person
/// @param person A instance of person
- (void)addPerson:(Person *)person;
/// To update internal mutbable set for removing a person
/// @param person A instance of person
- (void)removePerson:(Person *)person;
@end
NS_ASSUME_NONNULL_END
// The person.m file
#import "Person.h"
@interface Person ()
@property(nonatomic, strong) NSMutableSet<Person *> *friends;
@end
@implementation Person
#pragma mark - Initalizaiton Methods
- (instancetype)initWithName:(NSString *)name {
self = [super init];
if (!self) {
return nil;
}
if(!name || name.length < 1) {
name = @"Augus";
}
_name = name;
// Warn: Do not self.persons way to init. But do u know reason?
_friends = [NSMutableSet set];
return self;
}
#pragma mark - Private Methods
- (void)addPerson:(Person *)person {
// Check param safe
if (!person) {
return;
}
[self.friends addObject:person];
}
- (void)removePerson:(Person *)person {
if (!person) {
return;
}
[self.friends removeObject:person];
}
#pragma mark - Copy Methods
- (id)copyWithZone:(NSZone *)zone {
// need copy object
Person *copy = [[Person allocWithZone:zone] initWithName:_name];
return copy;
}
- (id)deepCopy {
Person *copy = [[[self class] alloc] initWithName:_name];
copy->_persons = [[NSMutableSet alloc] initWithSet:_friends copyItems:YES];
return copy;
}
#pragma mark - Lazy Load
- (NSMutableSet *)friends {
if (!_friends) {
_friends = [NSMutableSet set];
}
return _friends;
}
@end
类的性能很简略,初始化的时候须要外层传入name进行初始化,如果name非法则进行默认值的解决
- 类外部保护了一个可变汇合用来寄存好友
- 内部提供了新增和移除的两个办法
-
- (id)copyWithZone:(NSZone *)zone;中的实现就是简略的一个copy性能
- 而deepCopy是对可变汇合的深层复制,至于起因,咱们会在延展中举例说明,这里先搁置
03 copy底层实现
之前的文档中说过,想要看底层的实现那就用clang -rewrite-objc main.m看源码
为了不便测试和查看,咱们新建一个TestCopy的类继承NSObject,而后在TestCopy.m中只加如下代码
#import "TestCopy.h"
@interface TestCopy ()
@property(nonatomic, copy) NSString *augusCopy;
@end
@implementation TestCopy
@end
而后在终端执行$ clang -rewrite-objc TestCopy.m命令
接下来咱们进行源码剖析
// augusCopy's getter function
static NSString * _I_TestCopy_augusCopy(TestCopy * self, SEL _cmd) { return (*(NSString **)((char *)self + OBJC_IVAR_$_TestCopy$_augusCopy)); }
// augusCopy's setter function
static void _I_TestCopy_setAugusCopy_(TestCopy * self, SEL _cmd, NSString *augusCopy) { objc_setProperty (self, _cmd, __OFFSETOFIVAR__(struct TestCopy, _augusCopy), (id)augusCopy, 0, 1); }
总结:copy的getter是依据地址偏移找到对应的实例变量进行返回,那么objc_setProperty又是怎么实现的呢?
objc_setProperty在.cpp中没有找到,在[Apple源码](链接附文后)中找到了答案,咱们来看下
// self: The current instance
// _cmd: The setter's function name
// offset: The offset for self that find the instance property
// newValue: The new value that outer input
// atomic: Whether atomic or nonatomic,it is nonatomic here
// shouldCopy: Whether should copy or not
void
objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue,
BOOL atomic, signed char shouldCopy)
{
objc_setProperty_non_gc(self, _cmd, offset, newValue, atomic, shouldCopy);
}
void objc_setProperty_non_gc(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy)
{
bool copy = (shouldCopy && shouldCopy != MUTABLE_COPY);
bool mutableCopy = (shouldCopy == MUTABLE_COPY);
reallySetProperty(self, _cmd, newValue, offset, atomic, copy, mutableCopy);
}
看到外部又调用了objc_setProperty_non_gc办法,这里次要看下这个办法外部的实现,前五个参数和开始的传入统一,最初的两个参数是由shouldCopy决定,shouldCopy在这里是0 or 1,咱们现思考以后的状况,
- 如果shouldCopy=0,那么copy=NO,mutableCopy=NO
- 如果shouldCopy=1,那么copy=YES,mutableCopy=NO
上面持续reallySetProperty的实现
static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy)
{
id oldValue;
id *slot = (id*) ((char*)self + offset);
if (copy) {
newValue = [newValue copyWithZone:NULL];
} else if (mutableCopy) {
newValue = [newValue mutableCopyWithZone:NULL];
} else {
if (*slot == newValue) return;
newValue = objc_retain(newValue);
}
if (!atomic) {
oldValue = *slot;
*slot = newValue;
} else {
spin_lock_t *slotlock = &PropertyLocks[GOODHASH(slot)];
_spin_lock(slotlock);
oldValue = *slot;
*slot = newValue;
_spin_unlock(slotlock);
}
objc_release(oldValue);
}
基于本例子中的状况,copy=YES,最初还是调用了newValue = [newValue copyWithZone:NULL];,如果copy=NO and mutableCopy=NO,那么最初会调用newValue = objc_retain(newValue);
objc_retain的实现
id objc_retain(id obj) { return [obj retain]; }
总结:用copy润饰的属性,赋值的时候,不论自身是可变与不可变,赋值给属性之后的都是不可变的。
延展之深浅拷贝
01 非汇合类对象
在iOS下咱们常常听到深拷贝(内容拷贝)或者浅拷贝(指针拷贝),对于这些操作,咱们将针对汇合类对象和非汇合类对象进行copy和 mutableCopy试验。
类簇:Class Clusters
- an architecture that groups a number of private, concrete subclasses under a public, abstract superclass. (一个在共有的形象超类下设置一组公有子类的架构);
- Class cluster 是 Apple 对形象工厂设计模式的称说。应用抽象类初始化返回一个具体的子类的模式的益处就是让调用者只须要晓得抽象类凋谢进去的API的作用,而不须要晓得子类的背地简单的逻辑。验证论断过程的类簇对应关系请看这篇 [Class Clusters 文档](链接附文后)。
NSString
NSString *str = @"augusStr";
NSString *copyAugus = [str copy];
NSString *mutableCopyAugus = [str mutableCopy];
NSLog(@"str:(%@<%p>: %p): %@",[str class],&str,str,str);
NSLog(@"copyAugus str:(%@<%p>: %p): %@",[copyAugus class],©Augus,copyAugus,copyAugus);
NSLog(@"mutableCopyAugus str:(%@<%p>: %p): %@",[mutableCopyAugus class],&mutableCopyAugus,mutableCopyAugus,mutableCopyAugus);
// 控制台输入
2021-09-03 14:51:49.263571+0800 TestBlock[4573:178396] augus str(__NSCFConstantString<0x7ffee30a1008>: 0x10cb63198): augusStr
2021-09-03 14:51:49.263697+0800 TestBlock[4573:178396] copyAugus str(__NSCFConstantString<0x7ffee30a1000>: 0x10cb63198): augusStr
2021-09-03 14:51:49.263808+0800 TestBlock[4573:178396] mutableCopyAugus str(__NSCFString<0x7ffee30a0ff8>: 0x6000036bcfc0): augusStr
论断:str和copyAugus打印进去的内存地址是一样的,都是0x10cb63198且类名雷同都是__NSCFConstantString,表明都是浅拷贝,都是NSString;变量mutableCopyAugus打印进去的内存地址和类名都不统一,所以是生成了新的对象。
NSMutableString
NSMutableString *str = [NSMutableString stringWithString:@"augusMutableStr"];
NSMutableString *copyStr = [str copy];
NSMutableString *mutableCopyStr = [str mutableCopy];
NSLog(@"str:(%@<%p>: %p): %@",[str class],&str,str,str);
NSLog(@"copyStr: (%@<%p>: %p): %@",[copyStr class],©Str,copyStr,copyStr);
NSLog(@"mutableCopyStr: (%@<%p>: %p): %@",[mutableCopyStr class],&mutableCopyStr,mutableCopyStr,mutableCopyStr);
// 控制台输入
2021-09-03 15:31:56.105642+0800 TestBlock[4778:198224] str:(__NSCFString<0x7ffeeaa34008>: 0x600001a85fe0): augusMutableStr
2021-09-03 15:31:56.105804+0800 TestBlock[4778:198224] copyStr: (__NSCFString<0x7ffeeaa34000>: 0x600001a86400): augusMutableStr
2021-09-03 15:31:56.105901+0800 TestBlock[4778:198224] mutableCopyStr: (__NSCFString<0x7ffeeaa33ff8>: 0x600001a86070): augusMutableStr
论断:str和copyStr和mutableCopyStr打印进去的内存地址都不一样的,然而生成的类簇都是__NSCFString,也就是NSMutableString。
02 汇合类对象
本文对NSMutableSet展开讨论,所以只对该类进行测试。
NSSet
Person *p1 = [[Person alloc] init];
Person *p2 = [[Person alloc] init];
Person *p3 = [[Person alloc] init];
NSSet *set = [[NSSet alloc] initWithArray:@[p1,p2,p3]];
NSSet *copySet = [set copy];
NSSet *mutableCopySet = [set mutableCopy];
NSLog(@"set:(%@<%p>: %p): %@",[set class],&set,set,set);
NSLog(@"copySet: (%@<%p>: %p): %@",[copySet class],©Set,copySet,copySet);
NSLog(@"mutableCopySet: (%@<%p>: %p): %@",[mutableCopySet class],&mutableCopySet,mutableCopySet,mutableCopySet);
// 控制台输入
2021-09-03 16:11:36.590338+0800 TestBlock[4938:219837] set:(__NSSetI<0x7ffeef3f7fd0>: 0x6000007322b0): {(
<Person: 0x600000931e00>,
<Person: 0x600000931e20>,
<Person: 0x600000932000>
)}
2021-09-03 16:11:36.590479+0800 TestBlock[4938:219837] copySet: (__NSSetI<0x7ffeef3f7fc8>: 0x6000007322b0): {(
<Person: 0x600000931e00>,
<Person: 0x600000931e20>,
<Person: 0x600000932000>
)}
2021-09-03 16:11:36.590614+0800 TestBlock[4938:219837] mutableCopySet: (__NSSetM<0x7ffeef3f7fc0>: 0x600000931fa0): {(
<Person: 0x600000931e00>,
<Person: 0x600000932000>,
<Person: 0x600000931e20>
)}
论断:set和copySet打印进去的内存地址是统一的0x6000007322b0,类簇都是__NSSetI阐明是浅拷贝,没有生成新对象,也都属于类 NSSet;mutableCopySet的内存地址和类簇都不同,所以是深拷贝,生成了新的对象,属于类NSMutablSet;汇合外面的元素地址都是一样的。
NSMutableSet
NSMutableSet *set = [[NSMutableSet alloc] initWithArray:@[p1,p2,p3]];
NSMutableSet *copySet = [set copy];
NSMutableSet *mutableCopySet = [set mutableCopy];
NSLog(@"set:(%@<%p>: %p): %@",[set class],&set,set,set);
NSLog(@"copySet: (%@<%p>: %p): %@",[copySet class],©Set,copySet,copySet);
NSLog(@"mutableCopySet: (%@<%p>: %p): %@",[mutableCopySet class],&mutableCopySet,mutableCopySet,mutableCopySet);
// 控制台输入
2021-09-03 16:33:35.573557+0800 TestBlock[5043:232294] set:(__NSSetM<0x7ffeefb78fd0>: 0x600002b99640): {(
<Person: 0x600002b99620>,
<Person: 0x600002b99600>,
<Person: 0x600002b995e0>
)}
2021-09-03 16:33:35.573686+0800 TestBlock[5043:232294] copySet: (__NSSetI<0x7ffeefb78fc8>: 0x6000025e54a0): {(
<Person: 0x600002b99620>,
<Person: 0x600002b99600>,
<Person: 0x600002b995e0>
)}
2021-09-03 16:33:35.573778+0800 TestBlock[5043:232294] mutableCopySet: (__NSSetM<0x7ffeefb78fc0>: 0x600002b99680): {(
<Person: 0x600002b99620>,
<Person: 0x600002b99600>,
<Person: 0x600002b995e0>
)}
论断:set和copySet和mutableCopySet的内存地址都不一样,阐明操作都是深拷贝;汇合外面的元素地址都是一样的
03 论断剖析
- NSMutable*结尾的类不要用copy属性去润饰,因为每次赋值操作拷贝进去的都是不可变汇合类
- 汇合类的copy和mutableCopy操作,对象外面的元素不会产生拷贝,只会对容器层面拷贝,也称之为单层深拷贝
一次解体定位,一次源码之旅,一系列拷贝操作,根本能够把文中提到的问题说分明;遇到问题不要怕刨根问底,因为问底的止境就是无尽的光明。
发表回复