熟悉使用Java或者C++等其它語言的人,在使用Objective-C的時(shí)候會(huì)發(fā)現(xiàn)丢间,Objective-C沒有提供一個(gè)靜態(tài)數(shù)組數(shù)據(jù)結(jié)構(gòu)的封裝,比如無法實(shí)現(xiàn)如下的代碼:
class Untitled {
public static void main(String[] args) {
Person[] elements = new Person[8];
elements[3] = new Person();
System.out.println(elements[0]); // null
System.out.println(elements[3]); // Person()
}
}
class Person {
public String toString() {
return "Person()";
}
}
Objective-C要自定義實(shí)現(xiàn)一個(gè)可實(shí)用的靜態(tài)數(shù)組驹针,需要實(shí)現(xiàn)以下需求:
- 數(shù)組能夠存儲(chǔ)對(duì)象指針烘挫。
- 數(shù)組需要維持對(duì)象的引用計(jì)數(shù)。
- 數(shù)組需要支持范型柬甥。
- 數(shù)組需要支持下標(biāo)和常用數(shù)組接口的實(shí)現(xiàn)饮六。
- 數(shù)組需要支持for-in快速遍歷。
- 數(shù)組需要支持枚舉遍歷暗甥。
- 數(shù)組需要支持拷貝喜滨。
頭文件的聲明,JKRArray.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface JKRArray<ObjectType> : NSObject<NSFastEnumeration, NSCopying> {
@private
void ** _array;
NSUInteger _length;
}
- (instancetype)init __unavailable;
+ (instancetype)new __unavailable;
+ (instancetype)arrayWithLength:(NSUInteger)length;
- (instancetype)initWithLength:(NSUInteger)length;
- (NSUInteger)length;
- (void)setObject:(nullable ObjectType)object AtIndex:(NSUInteger)index;
- (nullable ObjectType)objectAtIndex:(NSUInteger)index;
- (void)removeObjectAtIndex:(NSUInteger)index;
- (NSUInteger)indexOfObject:(nullable ObjectType)object;
- (BOOL)containsObject:(ObjectType)object;
@end
@interface JKRArray<ObjectType> (JKRExtendedArray)
- (void)enumerateObjectsUsingBlock:(void (^)(_Nullable ObjectType obj, NSUInteger idx, BOOL *stop))block;
- (_Nullable ObjectType)objectAtIndexedSubscript:(NSUInteger)idx;
- (void)setObject:(_Nullable ObjectType)obj atIndexedSubscript:(NSUInteger)idx;
@end
@interface JKRArray<ObjectType> (NSGenericFastEnumeraiton) <NSFastEnumeration>
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained _Nullable [_Nonnull])buffer count:(NSUInteger)len;
@end
NS_ASSUME_NONNULL_END
內(nèi)部的實(shí)現(xiàn)撤防,這里要注意的就是需要將JKRArray.m改成JKRArray.mm虽风。
#import "JKRArray.h"
@implementation JKRArray
#pragma mark - 初始化
+ (instancetype)arrayWithLength:(NSUInteger)length {
return [[[self alloc] initWithLength:length] autorelease];
}
- (instancetype)initWithLength:(NSUInteger)length {
self = [super init];
_length = length;
_array = new void*[length]();
return self;
}
#pragma mark - dealloc
- (void)dealloc {
for (NSUInteger i = 0; i < _length; i++) {
id object = [self objectAtIndex:i];
if (object) [object release];
}
delete _array;
// NSLog(@"<%@, %p> dealloc", self.class, self);
[super dealloc];
}
#pragma mark - 返回長(zhǎng)度
- (NSUInteger)length {
return _length;
}
#pragma mark - 添加元素
- (void)setObject:(id)object AtIndex:(NSUInteger)index {
[self checkRangeWithIndex:index];
id oldObject = [self objectAtIndex:index];
if (oldObject == object) return;
if (oldObject != nil) [oldObject release];
if (object) [object retain];
*(_array + index) = (__bridge void *)object;
}
#pragma mark - 獲取元素
- (id)objectAtIndex:(NSUInteger)index {
[self checkRangeWithIndex:index];
id object = (__bridge id)(*(_array + index));
return object;
}
#pragma mark - 刪除元素
- (void)removeObjectAtIndex:(NSUInteger)index {
[self checkRangeWithIndex:index];
id object = (__bridge id)(*(_array + index));
if (object) [object release];
*(_array + index) = 0;
}
#pragma mark - 元素在數(shù)組中存儲(chǔ)的第一個(gè)下標(biāo)
- (NSUInteger)indexOfObject:(id)object {
__block NSUInteger index = NSUIntegerMax;
[self enumerateObjectsUsingBlock:^(id _Nullable obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (object == obj) {
index = idx;
*stop = YES;
} else if ([object isEqual:obj]){
index = idx;
*stop = YES;
}
}];
return index;
}
#pragma mark - 是否包含
- (BOOL)containsObject:(id)object {
NSUInteger index = [self indexOfObject:object];
return index < _length;
}
#pragma mark - 枚舉
- (void)enumerateObjectsUsingBlock:(void (^)(id _Nullable, NSUInteger, BOOL * _Nonnull))block {
BOOL stop = NO;
for (NSUInteger i = 0; i < _length && !stop; i++) {
id object = [self objectAtIndex:i];
block(object, i, &stop);
}
}
#pragma mark - 邊界檢查
- (void)checkRangeWithIndex:(NSUInteger)index {
if (index < 0 || index >= _length) NSAssert(NO, @"Index: %zd, Length: %zd", index, _length);
}
#pragma mark - 支持?jǐn)?shù)組運(yùn)算符
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
return [self objectAtIndex:idx];
}
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx {
[self setObject:obj AtIndex:idx];
}
#pragma mark - 快速遍歷
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id _Nullable [])buffer count:(NSUInteger)len {
if (state->state > 0) return 0;
state->mutationsPtr = (unsigned long*)self;
NSUInteger retCount = state->extra[0];
state->itemsPtr = (id *)(_array + state->extra[1]);
if (retCount == 0) retCount = _length;
if (retCount > len) {
state->extra[0] = retCount - len;
state->extra[1] += len;
retCount = len;
} else {
state->state++;
}
return retCount;
}
#pragma mark - 打印
- (NSString *)description {
NSMutableString *mutableString = [NSMutableString string];
[mutableString appendString:[NSString stringWithFormat:@"<%@: %p>: \nlength: %zd\n{\n", self.class, self, _length]];
for (NSUInteger i = 0; i < _length; i++) {
if (i) [mutableString appendString:@"\n"];
id object = [self objectAtIndex:i];
if (object) {
[mutableString appendString:@" "];
[mutableString appendString:[object description]];
} else {
[mutableString appendString:@" "];
[mutableString appendString:@"Null"];
}
}
[mutableString appendString:@"\n}"];
return mutableString;
}
- (id)copyWithZone:(NSZone *)zone {
JKRArray *array = [[JKRArray alloc] initWithLength:_length];
for (NSUInteger i = 0; i < _length; i++) {
array[i] = self[i];
}
return array;
}
@end
代碼測(cè)試:
JKRArray *array = [JKRArray arrayWithLength:6];
array[2] = [Person new];
NSLog(@"%@", array);
打印:
<JKRArray: 0x1006079f0>:
length: 6
{
Null
Null
<Person: 0x10286bc60>
Null
Null
Null
}