Objective-C静态数组的实现

熟悉使用Java或者C++等其它语言的人,在使用Objective-C的时候会发现,Objective-C没有提供一个静态数组数据结构的封装,比如无法实现如下的代码:


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要自定义实现一个可实用的静态数组,需要实现以下需求:

  1. 数组能够存储对象指针。
  2. 数组需要维持对象的引用计数。
  3. 数组需要支持范型。
  4. 数组需要支持下标和常用数组接口的实现。
  5. 数组需要支持for-in快速遍历。
  6. 数组需要支持枚举遍历。
  7. 数组需要支持拷贝。

头文件的声明,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

内部的实现,这里要注意的就是需要将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 - 返回长度
- (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 - 元素在数组中存储的第一个下标
- (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 - 支持数组运算符
- (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

代码测试:

JKRArray *array = [JKRArray arrayWithLength:6];
array[2] = [Person new];
NSLog(@"%@", array);

打印:
<JKRArray: 0x1006079f0>: 
length: 6
{
   Null
   Null
   <Person: 0x10286bc60>
   Null
   Null
   Null
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。