前言
複習下數組的使用方式,仿照List用oc實現下數組的增刪改查
功能
- 初始化時給定數組的容量
- 插入數據
- 刪除數據
- 根據下標返回數據
代碼
-
聲明頭文件
頭文件中包含了6個對象方法,如下:-
initWithCapacity
用於初始化數組容量 -
find
根據下標查找數據 -
remove
根據下標刪除數據 -
insert
根據下標插入數據 -
add
尾部追加數據 -
printAll
打印所有數據
-
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface CustomArray : NSObject
//初始化方法
- (instancetype) initWithCapacity: (NSUInteger) capacity;
//根據下標返回對應的值
- (id)find:(NSUInteger) index;
//根據下標刪除對應的值
- (void)remove:(NSUInteger) index;
//插入指定位置
- (void)insert:(id)anObject atIndex:(NSUInteger) index;
//尾部追加
- (void)add: (id)anObject;
//打印所有
- (void)printAll;
@end
NS_ASSUME_NONNULL_END
-
各個方法的實現
-
定義成員變量
@implementation MyArray { //可變數組 @private NSMutableArray *_data; //起始容量 NSUInteger _capacity; //數組中存儲的數據大小 NSUInteger _count; }
-
initWithCapacity
初始化,傳入起始容量。
- (instancetype)initWithCapacity:(NSUInteger)capacity { self = [super init]; if (self) { _data = [NSMutableArray arrayWithCapacity:capacity]; _capacity = capacity; _count = 0; } return self; }
-
find
根據下標返回元素
- (id)find:(NSUInteger)index { if (index >= _count) { return nil; } return _data[index]; }
-
remove
根據下標,刪除數據
- (void)remove:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index out of rang."]; } for (NSUInteger i = index; i < _count - 1; i++) { _data[i] = _data[i + 1]; } _count--; }
刪除數據時,後邊的元素依次向前移一個位置,同時,總數-1
-
insert
根據下標,插入數據
- (void)insert:(id)anObject atIndex:(NSUInteger)index { if (index >= _count || _capacity == _count) { [NSException raise:NSRangeException format:@"Index out of range."]; } for (NSUInteger i = _count - 1; i >= index; i--) { _data[i + 1] = _data[i]; } _data[index] = anObject; _count++; }
插入數據時,後邊的元素依次向後一個位置,同時,總數+1
-
add
添加一個數據
- (void)add:(id)anObject { if (_count == _capacity) { [NSException raise:NSRangeException format:@"Array is full."]; } [_data addObject:anObject]; _count++; }
-
printAll
- (void)printAll { for (id obj in _data) { NSLog(@"%@",obj); } }
-
所有的操作,一定要注意**下標**的判斷!