1.我们先来看看CFArrayRef的数据结构
//保存数组元素的指针
struct __CFArrayBucket {
const void *_item;
};
//mutableArray的deque
struct __CFArrayDeque {
uintptr_t _leftIdx;//数组在deque中开头的位置
uintptr_t _capacity;//数组容量
/* struct __CFArrayBucket buckets follow here */
};
//CFArrayRef的结构体
struct __CFArray {
CFRuntimeBase _base;//runtime基本结构体,每个CF数据都包含
CFIndex _count; //数组元素个数
CFIndex _mutations; //变化次数调用_CFArrayReplaceValues时 +1
int32_t _mutInProgress;
__strong void *_store; /* can be NULL when MutableDeque */
};
这个deque就是可变数组元素的存储方式。
2.下面我们来看看数组是怎么插入元素的:
//这里我们简化一下
void CFArrayInsertValueAtIndex(CFMutableArrayRef array, CFIndex
//调用replace来插入
_CFArrayReplaceValues(array, CFRangeMake(idx, 0), &value, 1);
}
//我们再来看看replace
void _CFArrayReplaceValues(CFMutableArrayRef array, CFRange range, const void **newValues, CFIndex newCount) {
const CFArrayCallBacks *cb;//release/retain/equil/copyDescription函数指针结构体
CFIndex idx, cnt, futureCnt;
const void **newv, *buffer[256];
cnt = __CFArrayGetCount(array);//cnt 获取数组当前元素个数
futureCnt = cnt - range.length + newCount; //替换后新的元素个数
cb = __CFArrayGetCallBacks(array);//获取数组回调
CFAllocatorRef allocator = __CFGetAllocator(array);
//如果retain方法存在
if (NULL != cb->retain && !hasBeenFinalized(array)) {
//替换的个数小于等于256则用栈上的buffer,否则在堆上重新分配
newv = (newCount <= 256) ? (const void **)buffer : (const void **)CFAllocatorAllocate(kCFAllocatorSystemDefault, newCount * sizeof(void *), 0); // GC OK
//把新加入数组的对象retain一下
for (idx = 0; idx < newCount; idx++) {
newv[idx] = (void *)INVOKE_CALLBACK2(cb->retain, allocator, (void *)newValues[idx]);
}
} else {
newv = newValues;
}
array->_mutations++;//变化次数加1
//现在有A、B、C三个区域 A+C是原来的数组从Range.location分割的2部分 B是插入中间的区域
//先把要替换的释放掉
if (0 < range.length) {
__CFArrayReleaseValues(array, range, false);
}
//如果array->_store不存在 则申请一个内存
if (NULL == array->_store) {
//如果_store不存在
if (0 <= futureCnt) {
struct __CFArrayDeque *deque;
//获取替换或插入后新的数组容量
CFIndex capacity = __CFArrayDequeRoundUpCapacity(futureCnt);
//deque的大小,__CFArrayDeque结构体+数组长度
CFIndex size = sizeof(struct __CFArrayDeque) + capacity * sizeof(struct __CFArrayBucket);
//申请一个新的deque
deque = (struct __CFArrayDeque *)CFAllocatorAllocate((allocator), size, isStrongMemory(array) ? __kCFAllocatorGCScannedMemory : 0);
if (__CFOASafe) __CFSetLastAllocationEventName(deque, "CFArray (store-deque)");
//数组连续放在deque的中间,_leftIdx表示数组的左边界
deque->_leftIdx = (capacity - newCount) / 2;
//保存数组的容量
deque->_capacity = capacity;
//array->_store = deque
__CFAssignWithWriteBarrier((void **)&array->_store, (void *)deque);
if (CF_IS_COLLECTABLE_ALLOCATOR(allocator)) auto_zone_release(objc_collectableZone(), deque); // GC: now safe to unroot the array body.
}
} else { // 如果Deque存在
//如果要被替换的元素个数不等于替换的元素个数
if (range.length != newCount) {
//memmove+memset,改变array老元素位置
__CFArrayRepositionDequeRegions(array, range, newCount);
}
}
// copy in new region B elements
if (0 < newCount) {
//获取array中的deque
struct __CFArrayDeque *deque = (struct __CFArrayDeque *)array->_store;
//获取保存元素开始的位置
struct __CFArrayBucket *raw_buckets = (struct __CFArrayBucket *)((uint8_t *)deque + sizeof(struct __CFArrayDeque));
//把新的数据copy到空出来的位置
objc_memmove_collectable(raw_buckets + deque->_leftIdx + range.location, newv, newCount * sizeof(struct __CFArrayBucket));
}
//设置array大小为当前元素个数
__CFArraySetCount(array, futureCnt);
}
//那么我们再来看看插入元素的空位怎么移出来的
static void __CFArrayRepositionDequeRegions(CFMutableArrayRef array, CFRange range, CFIndex newCount) {
// newCount elements are going to replace the range, and the result will fit in the deque
struct __CFArrayDeque *deque = (struct __CFArrayDeque *)array->_store;
struct __CFArrayBucket *buckets;
CFIndex cnt, futureCnt, numNewElems;
CFIndex L, A, B, C, R;
//从数组获取deque开始的位置,也就是数组头
buckets = (struct __CFArrayBucket *)((uint8_t *)deque + sizeof(struct __CFArrayDeque));
//获取数组容量
cnt = __CFArrayGetCount(array);
//新的数组容量
futureCnt = cnt - range.length + newCount;
//数组头离deque头的距离
L = deque->_leftIdx; // length of region to left of deque
//替换左边的长度
A = range.location; // length of region in deque to left of replaced range
//替换的长度
B = range.length; // length of replaced range
//替换右边的长度
C = cnt - B - A; // length of region in deque to right of replaced range
//deque右边剩余长度
R = deque->_capacity - cnt - L; // length of region to right of deque
//需要新增加的长度
numNewElems = newCount - B;
CFIndex wiggle = deque->_capacity >> 17;
if (wiggle < 4) wiggle = 4;
//数组增大,需要重新申请内存
if (deque->_capacity < (uint32_t)futureCnt || (cnt < futureCnt && L + R < wiggle)) {
// must be inserting or space is tight, reallocate and re-center everything
//得到新的数组容量大小 capacity = 1<<(futureCnt + wiggle) 如果小于4就直接等于4
CFIndex capacity = __CFArrayDequeRoundUpCapacity(futureCnt + wiggle);
//新的容量占用的字节数
CFIndex size = sizeof(struct __CFArrayDeque) + capacity * sizeof(struct __CFArrayBucket);
CFAllocatorRef allocator = __CFGetAllocator(array);
Boolean collectableMemory = CF_IS_COLLECTABLE_ALLOCATOR(allocator);
//如果空间不够 重新分配deque
struct __CFArrayDeque *newDeque = (struct __CFArrayDeque *)CFAllocatorAllocate(allocator, size, isStrongMemory(array) ? __kCFAllocatorGCScannedMemory : 0);
//获取重新分配后的开始存储的位置
struct __CFArrayBucket *newBuckets = (struct __CFArrayBucket *)((uint8_t *)newDeque + sizeof(struct __CFArrayDeque));
CFIndex oldL = L;
CFIndex newL = (capacity - futureCnt) / 2;
CFIndex oldC0 = oldL + A + B;
CFIndex newC0 = newL + A + newCount;
newDeque->_leftIdx = newL;
newDeque->_capacity = capacity;
//把替换位置2边的元素移动到对应位置
if (0 < A) objc_memmove_collectable(newBuckets + newL, buckets + oldL, A * sizeof(struct __CFArrayBucket));
if (0 < C) objc_memmove_collectable(newBuckets + newC0, buckets + oldC0, C * sizeof(struct __CFArrayBucket));
//把重新分配的deque array->_store = newDeque
__CFAssignWithWriteBarrier((void **)&array->_store, (void *)newDeque);
//释放原来的deque
if (!collectableMemory && deque) CFAllocatorDeallocate(allocator, deque);
if (CF_IS_COLLECTABLE_ALLOCATOR(allocator)) auto_zone_release(objc_collectableZone(), newDeque);
return;
}
//在空余长度足够的情况下 移动分割出的短的部分
//AB是原来的数组被range.location分割的,C是被替换的部分
if ((numNewElems < 0 && C < A) || (numNewElems <= R && C < A)) { // move C
// deleting: C is smaller
// inserting: C is smaller and R has room
//从deque的开头到被替换末尾的位置
CFIndex oldC0 = L + A + B;
//从deque的开头到替换末尾的位置
CFIndex newC0 = L + A + newCount;
//如果替换右边的长度 > 0
if (0 < C) objc_memmove_collectable(buckets + newC0, buckets + oldC0, C * sizeof(struct __CFArrayBucket));
// GrP GC: zero-out newly exposed space on the right, if any
if (oldC0 > newC0) memset(buckets + newC0 + C, 0, (oldC0 - newC0) * sizeof(struct __CFArrayBucket));
} else if ((numNewElems < 0) || (numNewElems <= L && A <= C)) { // move A
// deleting: A is smaller or equal (covers remaining delete cases)
// inserting: A is smaller and L has room
CFIndex oldL = L;
CFIndex newL = L - numNewElems;
deque->_leftIdx = newL;
if (0 < A) objc_memmove_collectable(buckets + newL, buckets + oldL, A * sizeof(struct __CFArrayBucket));
// GrP GC: zero-out newly exposed space on the left, if any
if (newL > oldL) memset(buckets + oldL, 0, (newL - oldL) * sizeof(struct __CFArrayBucket));
} else {
//应该移动左边的但左边没有空间
//或者应该移动右边的但右边没有空间
// now, must be inserting, and either:
// A<=C, but L doesn't have room (R might have, but don't care)
// C<A, but R doesn't have room (L might have, but don't care)
// re-center everything
CFIndex oldL = L;
CFIndex newL = (L + R - numNewElems) / 2;
newL = newL - newL / 2;
CFIndex oldC0 = oldL + A + B;
CFIndex newC0 = newL + A + newCount;
deque->_leftIdx = newL;
if (newL < oldL) {
if (0 < A) objc_memmove_collectable(buckets + newL, buckets + oldL, A * sizeof(struct __CFArrayBucket));
if (0 < C) objc_memmove_collectable(buckets + newC0, buckets + oldC0, C * sizeof(struct __CFArrayBucket));
// GrP GC: zero-out newly exposed space on the right, if any
if (oldC0 > newC0) memset(buckets + newC0 + C, 0, (oldC0 - newC0) * sizeof(struct __CFArrayBucket));
} else {
if (0 < C) objc_memmove_collectable(buckets + newC0, buckets + oldC0, C * sizeof(struct __CFArrayBucket));
if (0 < A) objc_memmove_collectable(buckets + newL, buckets + oldL, A * sizeof(struct __CFArrayBucket));
// GrP GC: zero-out newly exposed space on the left, if any
if (newL > oldL) memset(buckets + oldL, 0, (newL - oldL) * sizeof(struct __CFArrayBucket));
}
}
}
总结:
1.可变数组存放在deque中
2.deque的前面2个数据保存数组开始位置在deque中的偏移和deque的容量大小
3.创建新的deque时把数组放在deque的中间,为了方便后面插入删除数据
4.插入数据时,插入的位置把数组分割成左右2部分(A/C),插入的部分为B
5.插入时如果需要增大空间,重新申请deque;如果A<=C并且左边空间足够,则A部分左移;如果A>C并且右边空间足够,则C部分右移;如果前面2种情况都不符合,则A、C都移动并且A+B+C合起来移动到deque的中间
3.数组判断是否包含某个元素
//判断包含某个元素
Boolean CFArrayContainsValue(CFArrayRef array, CFRange range, const void *value) {
CFIndex idx;
const CFArrayCallBacks *cb = CF_IS_OBJC(CFArrayGetTypeID(), array) ? &kCFTypeArrayCallBacks : __CFArrayGetCallBacks(array);
//循环遍历数组判断
for (idx = 0; idx < range.length; idx++) {
const void *item = CFArrayGetValueAtIndex(array, range.location + idx);
//如果地址相等bicb->equal函数返回相等([NSObject isEquil])
if (value == item || (cb->equal && INVOKE_CALLBACK2(cb->equal, value, item))) {
return true;
}
}
return false;
}