Objective-C的NSArray與NSMutableArray學習筆記

NSArray - 不可變數(shù)組

NSArray,繼承自NSObject,不可變數(shù)組,是一個對象,是任意類型對象地址的集合,不能存放簡單的數(shù)據(jù)類型(int, float, NSInteger…),除非通過一些方法把簡單數(shù)據(jù)類型變成對象。NSArray建立之后就不可修改。

需要注意的是NSArray下標越界不會有警告,但是運行會直接報錯,報錯信息如下:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndexedSubscript:]: index 3 beyond bounds [0 .. 2]'
NSArray提供的一些屬性
@property (readonly) NSUInteger count;

屬性描述 :只讀屬性,獲取數(shù)組中的對象數(shù)量

@property (nullable, nonatomic, readonly) ObjectType firstObject API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

屬性描述 : 只讀屬性,獲取數(shù)組中的第一個對象。如果數(shù)組為空,則返回nil

@property (nullable, nonatomic, readonly) ObjectType lastObject;

屬性描述 : 只讀屬性,獲取數(shù)組中的最后一個對象。如果數(shù)組為空,則返回nil

NSArray創(chuàng)建相關(guān)函數(shù)

可以在Objective-C或Swift中使用數(shù)組文字語法來創(chuàng)建包含給定對象的數(shù)組:

\color{red}{通過簡單的方式創(chuàng)建數(shù)組,例如:}

//空數(shù)組
NSArray *array6 = @[];
    
//3個元素
NSArray *array7 = @[@"111",@"222",@"333"];
- (instancetype)init NS_DESIGNATED_INITIALIZER;

函數(shù)描述 : 由子類實現(xiàn),以便在分配新對象(調(diào)用方)的內(nèi)存后立即對其進行初始化,init消息與alloc(或allocWithZone:)消息耦合在同一行代碼中。在某些情況下,init方法的自定義實現(xiàn)可能會返回一個替代對象。因此,在后續(xù)代碼中,必須始終使用init返回的對象,而不是alloc或allocWithZone:返回的對象。

在NSObject類中定義的init方法不進行初始化;它只是返回self。在可空性方面,調(diào)用者可以假設init的NSObject實現(xiàn)不返回nil。

返回值 : 初始化的對象,如果由于某種原因無法創(chuàng)建對象而不會導致異常,則為nil。

+ (instancetype)array;

函數(shù)描述創(chuàng)建并返回空數(shù)組

返回值 : 空數(shù)組。

\color{red}{創(chuàng)建一個空數(shù)組,例如:}

NSArray *array = [[NSArray alloc] init];
    
NSArray *array2 = [NSArray array];
+ (instancetype)arrayWithObject:(ObjectType)anObject;

函數(shù)描述創(chuàng)建并返回包含給定對象的數(shù)組

參數(shù) :

anObject : 一個對象。

返回值 :包含單個元素對象的數(shù)組。

+ (instancetype)arrayWithObjects:(ObjectType)firstObj, ... NS_REQUIRES_NIL_TERMINATION;

函數(shù)描述創(chuàng)建并返回包含參數(shù)列表中的對象的數(shù)組

參數(shù):

firstObj : 數(shù)組的第一個對象。

... : 逗號分隔的附加對象列表,以nil結(jié)尾。

返回值 : 包含參數(shù)列表中對象的數(shù)組。

\color{red}{通過指定對象創(chuàng)建數(shù)組,例如:}

 //只有一個元素
 NSArray *array3 = [NSArray arrayWithObject:@"aaa"];
    
 //有n個元素
 NSArray *array4 = [NSArray arrayWithObjects:@"1111",@"2222",@"333", nil];
+ (instancetype)arrayWithArray:(NSArray<ObjectType> *)array;

函數(shù)描述創(chuàng)建并返回一個數(shù)組,該數(shù)組包含另一個給定數(shù)組中的對象

參數(shù) :

array : 給定的數(shù)組。

返回值 : 包含數(shù)組中對象的數(shù)組。

\color{red}{通過指定數(shù)組創(chuàng)建數(shù)組(兩個數(shù)組內(nèi)容的一樣),例如:}

NSArray *array5 = [NSArray arrayWithArray:array4];
NSArray操作相關(guān)函數(shù)
- (ObjectType)objectAtIndex:(NSUInteger)index;

函數(shù)描述返回位于指定索引處的對象。如果索引超出數(shù)組末尾(即,如果索引大于或等于計數(shù)返回的值),則會引發(fā)NSRangeException。

參數(shù) :

index : 數(shù)組邊界內(nèi)的索引。

返回值 : 位于索引處的對象。

\color{red}{通過索引獲取相應的元素(下標要小于數(shù)組的count),例如:}

[array7 objectAtIndex:下標];
//簡單取值
array7[下標];
- (NSArray<ObjectType> *)objectsAtIndexes:(NSIndexSet *)indexes;

函數(shù)描述返回一個數(shù)組,該數(shù)組中的對象位于給定索引集指定的索引處。返回的對象按照索引中索引的升序排列,因此索引中索引較高的返回數(shù)組中的對象將跟隨索引中索引較小的對象。如果索引中的任何位置超出了數(shù)組的界限,則引發(fā)NSRangeException,索引為nil。

參數(shù) :

indexes : 給定索引集。

返回值 :在索引指定的索引處包含數(shù)組中的對象的數(shù)組。

\color{red}{獲取數(shù)組中的一部分元素,例如:}

NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
//初始化一個索引,NSIndexSet是一個集合類(索引的集合),但是集合里面不能有重復索引
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
//下標為0,長度為2
NSRange range = NSMakeRange(0, 2);
//構(gòu)造一個范圍的索引
indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
NSLog(@"%@",[array7 objectsAtIndexes:indexSet]);
- (NSUInteger)indexOfObject:(ObjectType)anObject;

函數(shù)描述返回對應數(shù)組值等于給定對象的最低索引。從索引0開始,數(shù)組中的每個元素都作為一個參數(shù)傳遞給isEqual:消息被發(fā)送給一個對象,直到找到匹配或者到達數(shù)組的末端。如果isEqual:(在NSObject協(xié)議中聲明)返回YES,則認為對象相等。

參數(shù) :

anObject : 一個對象。

返回值 : 對應數(shù)組值等于anObject的最低索引。如果數(shù)組中的對象都不等于anObject,則返回NSNotFound。

\color{red}{通過對象獲取在數(shù)組中的索引(通過元素獲取下標,例如:}

[array7 indexOfObject:要找的對象]
- (BOOL)containsObject:(ObjectType)anObject;

函數(shù)描述返回一個布爾值,該值指示給定對象是否存在于數(shù)組中。從索引0開始,檢查數(shù)組中的每個元素是否與對象相等,直到找到匹配項或到達數(shù)組的結(jié)尾。如果isEqual:返回YES,則視為對象相等。

要確定數(shù)組是否包含對象的特定實例,可以通過調(diào)用indexOfObjectIdenticalTo:方法并將返回值與NSNotFound進行比較來測試標識而不是相等性。

參數(shù) :

anObject : 要在數(shù)組中查找的對象。

返回值 : 如果數(shù)組中有對象,則為YES,否則為NO。

\color{red}{判斷數(shù)組中數(shù)組包含某個元素,例如:}

[array7 containsObject:要查找的對象]
- (BOOL)isEqualToArray:(NSArray<ObjectType> *)otherArray;

函數(shù)描述將調(diào)用方數(shù)組與另一個數(shù)組進行比較。如果兩個數(shù)組各自擁有相同數(shù)量的對象,并且每個數(shù)組中的給定索引處的對象滿足isEqual:test,則兩個數(shù)組具有相同的內(nèi)容。

參數(shù) :

otherArray : 一個數(shù)組。

返回值 : 如果otherArray的內(nèi)容等于調(diào)用方數(shù)組的內(nèi)容,則為YES,否則為NO。

\color{red}{判斷兩個數(shù)組內(nèi)容是否相同(元素順序也要相同),例如:}

NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
    
NSArray *array8 = @[@"111",@"222",@"333",@"444",@"555",@"666"];

if ([array7 isEqualToArray:array8]){
      NSLog(@"內(nèi)容完全相等");
}
else
{
      NSLog(@"內(nèi)容不完全相等");
}
- (NSArray<ObjectType> *)subarrayWithRange:(NSRange)range;

函數(shù)描述返回一個新數(shù)組,其中包含調(diào)用方數(shù)組中的元素,這些元素位于給定范圍指定的范圍內(nèi)。如果range不在調(diào)用方數(shù)組的元素范圍內(nèi),則引發(fā)NSRangeException。

參數(shù) :

range : 調(diào)用方數(shù)組中元素范圍內(nèi)的范圍。

返回值 : 包含調(diào)用方數(shù)組元素的新數(shù)組,這些元素在范圍指定的范圍內(nèi)。

\color{red}{截取數(shù)組中指定范圍的元素,例如:}

NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
NSRange range = NSMakeRange(0, 2);
NSLog(@"%@", [array7 subarrayWithRange:range]);
NSArray數(shù)組的遍歷

\color{red}{通過下標遍歷數(shù)組,例如:}

NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
for (int i = 0 ; i < array7.count; i++){
     NSLog(@"%@",array7[I]);
}

\color{red}{快速枚舉法(for in),例如:}

NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
    
for (NSString *str in array7) {
     NSLog(@"%@",str);
}

\color{red}{通過枚舉器遍歷}枚舉器是一種蘋果官方推薦的更加面向?qū)ο蟮囊环N遍歷方式,相比于for循環(huán),它具有高度解耦、面向?qū)ο蟆⑹褂梅奖愕葍?yōu)勢。例如:

NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
    
[array7 enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
     NSLog(@"%@",array7[idx]);
}];

\color{red}{正序輸出所有元素,例如:}

NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
//通過objectEnumerator向數(shù)組請求枚舉器
NSEnumerator *enumerator = [array7 objectEnumerator];
NSLog(@"%@",[enumerator allObjects]);

\color{red}{逆序輸出所有元素,例如:}

NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
//通過reverseObjectEnumerator向數(shù)組請求枚舉器
NSEnumerator *enumerator = [array7 reverseObjectEnumerator];
NSLog(@"%@",[enumerator allObjects]);

NSMutableArray - 可變數(shù)組

NSMutableArray,可變數(shù)組,是NSArray的子類,可以對數(shù)組進行加入、刪除或者替換元素,使用比NSArray更加方便,但缺少了NSArray的安全性

NSMutableArray創(chuàng)建相關(guān)函數(shù)

\color{red}{創(chuàng)建一個空數(shù)組,例如:}

NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
    
NSMutableArray *mutableArray2 = [NSMutableArray array];

\color{red}{通過指定對象創(chuàng)建數(shù)組,例如:}

//只有一個元素
NSMutableArray *mutableArray = [NSMutableArray arrayWithObject:@"111"];
NSLog(@"%@",mutableArray);
    
 //有n個元素
NSMutableArray *mutableArray2 = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333",@"4444", nil];
NSLog(@"%@",mutableArray2);
NSMutableArray操作相關(guān)函數(shù)
- (void)addObject:(ObjectType)anObject;

函數(shù)描述在數(shù)組末尾插入給定對象。如果對象為nil,則引發(fā)NSInvalidArgumentException。

參數(shù) :

anObject : 要添加到數(shù)組內(nèi)容末尾的對象。此值不能為nil。

\color{red}{向可變數(shù)組里面添加元素(在最后添加),例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObject:@"111"];
[mutableArray addObject:@"222"];
NSLog(@"%@",mutableArray);
- (void)insertObject:(ObjectType)anObject atIndex:(NSUInteger)index;

函數(shù)描述在給定索引處將給定對象插入數(shù)組的內(nèi)容。如果索引已被占用,則索引處和索引以外(大于等于給定索引的數(shù)組索引)的對象將通過向其索引中添加1來移動,以騰出空間。

注意,NSArray對象不像C數(shù)組。也就是說,即使在創(chuàng)建數(shù)組時指定了大小,也會將指定的大小視為“提示”,數(shù)組的實際大小仍然是0。這意味著不能在大于數(shù)組當前計數(shù)的索引處插入對象。例如,如果一個數(shù)組包含兩個對象,它的大小是2,因此可以在下標0、1或2處添加對象。索引3是非法的,超出了界限,如果試圖在索引3處添加對象(當數(shù)組大小為2時),NSMutableArray將引發(fā)異常。

參數(shù) :

anObject : 要添加到數(shù)組內(nèi)容的對象。此值不能為nil。如果對象為nil,則引發(fā)NSInvalidArgumentException。

index : 數(shù)組中插入對象的索引。此值不能大于數(shù)組中元素的計數(shù)。如果索引大于數(shù)組中的元素數(shù),則引發(fā)NSRangeException。

\color{red}{向可變數(shù)組中插入一個元素,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObject:@"111"];
[mutableArray insertObject:@"333" atIndex:0];
NSLog(@"%@",mutableArray);
- (void)insertObjects:(NSArray<ObjectType> *)objects atIndexes:(NSIndexSet *)indexes;

函數(shù)描述將提供數(shù)組中的對象插入到調(diào)用方數(shù)組中的指定索引處。在前面的插入之后,對象中的每個對象依次插入到調(diào)用方數(shù)組的索引中指定的相應位置。

參數(shù) :

objects : 要插入到調(diào)用方數(shù)組中的對象數(shù)組。

indexes :對象中的對象應插入的索引。索引中的位置計數(shù)必須等于對象計數(shù)。

\color{red}{向可變數(shù)組中插入多個元素,例如:}

    //不會越界
    NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];
    NSArray *newAdditions = [NSArray arrayWithObjects: @"a", @"b", nil];
    NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:5];
    [indexes addIndex:4];
    [array insertObjects:newAdditions atIndexes:indexes];
    NSLog(@"array: %@", array);
    
    //不會越界
    NSMutableArray *array2 = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];
    NSArray *newAdditions2 = [NSArray arrayWithObjects: @"a", @"b", @"c", nil];
    NSMutableIndexSet *indexes2 = [NSMutableIndexSet indexSetWithIndex:1];
    [indexes2 addIndex:2];
    [indexes2 addIndex:6];
    [array2 insertObjects:newAdditions2 atIndexes:indexes2];
    NSLog(@"array: %@", array2);
    
    //會越界
    NSMutableArray *array3 = [NSMutableArray arrayWithObjects: @"one", @"two", @"three", @"four", nil];
    NSArray *newAdditions3 = [NSArray arrayWithObjects: @"a", @"b", nil];
    NSMutableIndexSet *indexes3 = [NSMutableIndexSet indexSetWithIndex:6];
    [indexes3 addIndex:4];
    [array3 insertObjects:newAdditions3 atIndexes:indexes2];
    NSLog(@"array: %@", array3);
- (void)removeObjectAtIndex:(NSUInteger)index;

函數(shù)描述刪除索引處的對象。為了填補這個空白,索引之外(大于等于給定索引的數(shù)組索引)的所有元素都將通過從其索引中減去1來移動。

參數(shù) :

index : 從中移除數(shù)組中對象的索引。值不能超過數(shù)組的邊界。如果索引超出數(shù)組末尾,則引發(fā)異常NSRangeException。

\color{red}{刪除指定索引的元素,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
    
[mutableArray removeObjectAtIndex:1];
    
NSLog(@"%@",mutableArray);
- (void)removeLastObject;

函數(shù)描述刪除數(shù)組中索引值最高的對象

\color{red}{刪除最后一個元素,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
    
[mutableArray removeLastObject];
    
NSLog(@"%@",mutableArray);
- (void)removeObject:(ObjectType)anObject;

函數(shù)描述刪除給定對象數(shù)組中的所有引用。此方法通過使用isEqual:方法將對象與調(diào)用方數(shù)組中的對象進行比較來確定匹配。如果數(shù)組不包含對象,則該方法無效。

參數(shù) :

anObject : 要從數(shù)組中移除的對象。

\color{red}{根據(jù)指定對象來刪除元素,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
    
[mutableArray removeObject:@"222"];
    
NSLog(@"%@",mutableArray);
- (void)removeAllObjects;

函數(shù)描述清空數(shù)組中的所有元素

\color{red}{刪除所有元素,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
    
[mutableArray removeAllObjects];
    
NSLog(@"%@",mutableArray);
- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes;

函數(shù)描述從數(shù)組中刪除指定索引處的對象。此方法類似于removeObjectAtIndex:,但允許您通過一個操作有效地刪除多個對象。如果索引為nil,則此方法引發(fā)異常。

參數(shù) :

indexes : 要從數(shù)組中移除的對象的索引。索引指定的位置必須在數(shù)組的邊界內(nèi)。

\color{red}{一次性刪除所有指定下標的元素,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
    
//初始化一個索引,NSIndexSet是一個集合類(索引的集合),但是集合里面不能有重復索引
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
//下標為1,長度為2
NSRange range = NSMakeRange(1, 2);
//構(gòu)造一個范圍的索引
indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
    
[mutableArray removeObjectsAtIndexes:indexSet];
    
NSLog(@"%@",mutableArray);

\color{red}{刪除元素時,可以倒序遍歷數(shù)組,正序遍歷由于刪除元素時索引的變化,會造成刪除錯誤,例如:}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
    
    for (int i = 0; i < array.count; i++) {
        [array removeObjectAtIndex:i];
    }
    
    NSLog(@"%@",array);
    
    NSMutableArray *array2 = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
    
    [array2 enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [array2 removeObjectAtIndex:idx];
    }];
    
    NSLog(@"%@",array2);
}

屏幕快照 2019-09-26 下午11.52.54.png
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(ObjectType)anObject;

函數(shù)描述用一個對象替換索引處的對象

參數(shù) :

index : 要替換的對象的索引。此值不能超過數(shù)組的邊界。如果索引超出數(shù)組末尾,則引發(fā)NSRangeException。

\color{red}{根據(jù)下標替換元素,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
    
[mutableArray replaceObjectAtIndex:0 withObject:@"HelloWord"];
    
NSLog(@"%@",mutableArray);
- (void)replaceObjectsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray<ObjectType> *)objects;

函數(shù)描述替換調(diào)用方數(shù)組中指定位置處的對象,該位置由給定數(shù)組中的對象指定。索引中的索引按照與對象中的對象相同的順序使用。如果對象或索引為空,則此方法引發(fā)異常。

參數(shù) :

indexes : 要替換的對象的索引。

objects : 在由索引指定的索引處替換調(diào)用方數(shù)組中對象的對象。索引中的位置計數(shù)必須等于對象計數(shù)。

\color{red}{根據(jù)下標集合替換元素(多個元素替換),例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
    
NSMutableArray *mutableArray2 = [NSMutableArray arrayWithObjects:@"Hello",@"Word", nil];
    
 //初始化一個索引,NSIndexSet是一個集合類(索引的集合),但是集合里面不能有重復索引
 NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
//下標為1,長度為2
NSRange range = NSMakeRange(1, 2);
//構(gòu)造一個范圍的索引
indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
    
[mutableArray replaceObjectsAtIndexes:indexSet withObjects:mutableArray2];
    
NSLog(@"%@",mutableArray);
- (void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray<ObjectType> *)otherArray range:(NSRange)otherRange;

函數(shù)描述將調(diào)用方數(shù)組中的一個給定范圍內(nèi)指定的對象替換為另一個數(shù)組中給定范圍的的對象。range和otherRange的長度不必相等:如果range比otherRange長,則調(diào)用方數(shù)組中的額外對象將被刪除,如果otherRange比range長,則來自otherArray的額外對象被插入到調(diào)用方數(shù)組中。

參數(shù) :

range : 要在調(diào)用方數(shù)組中替換(或從調(diào)用方數(shù)組中刪除)的對象的范圍。

otherArray : 要從中選擇range中對象的替換項的對象數(shù)組。

otherRange : 可以從otherArray中選擇對象的范圍來替換range中的對象。

\color{red}{當前指定范圍的下標替換為指定數(shù)組中的元素,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
    
NSMutableArray *mutableArray2 = [NSMutableArray arrayWithObjects:@"Hello",@"Word",@"Object-C", nil];
    
//要替換目標數(shù)組的位置,下標為1,長度為2
NSRange range = NSMakeRange(1, 2);
    
//替換素材數(shù)組的位置,下標為0,長度為3
NSRange range2 = NSMakeRange(0, 3);
    
[mutableArray replaceObjectsInRange:range withObjectsFromArray:mutableArray2 range:range2];
 //當替換素材數(shù)組的下標位置大與要替換目標數(shù)組的下標位置時,該元素會插入到數(shù)組中
NSLog(@"%@",mutableArray);
- (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2;

函數(shù)描述在給定索引處交換數(shù)組中的對象

參數(shù) :

idx1 : 在索引idx2處替換對象的對象的索引。

idx2 : 在索引idx1處替換對象的對象的索引。

\color{red}{交換兩個元素,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
    
[mutableArray exchangeObjectAtIndex:0 withObjectAtIndex:2];
    
NSLog(@"%@",mutableArray);
- (void)setArray:(NSArray<ObjectType> *)otherArray;

函數(shù)描述將調(diào)用方數(shù)組的元素設置為其他給定數(shù)組中的元素

參數(shù) :

otherArray : 用來替換調(diào)用方數(shù)組內(nèi)容的對象數(shù)組。

\color{red}{設置數(shù)組元素,例如 :}

NSMutableArray *tableArray = [[NSMutableArray alloc]initWithObjects:@"Hello",@"Word", nil];
NSArray *array = @[@"你好",@"世界"];
[tableArray setArray:array];
NSLog(@"%@",array);
- (void)sortUsingComparator:(NSComparator NS_NOESCAPE)cmptr API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

函數(shù)描述使用給定NSComparator塊指定的比較方法對調(diào)用方數(shù)組排序

參數(shù) :

cmptr :比較器塊。

\color{red}{利用sortUsingComparator函數(shù)進行排序,例如 :}

//NSComparisonResult的枚舉值如下 :
typedef NS_CLOSED_ENUM(NSInteger, NSComparisonResult) {
    NSOrderedAscending = -1L,//左操作數(shù)小于右操作數(shù)。
    NSOrderedSame,//兩個操作數(shù)相等。
    NSOrderedDescending//左操作數(shù)大于右操作數(shù)。
};

NSMutableArray *tableArray = [[NSMutableArray alloc]initWithObjects:@"3",@"2",@"5",@"2",@"7", nil];
[tableArray sortUsingComparator:^NSComparisonResult(NSString  *_Nonnull str1, NSString * _Nonnull str2) {
        
        if ([str1 longLongValue] < [str2 longLongValue]){
            
            return NSOrderedDescending;
        }
        else if ([str1 longLongValue] == [str2 longLongValue]){
            
            return NSOrderedSame;
        }else{
            
            return NSOrderedAscending;
        }
    }];
 
    NSLog(@"%@",tableArray);

\color{red}{利用NSSortDescriptor進行數(shù)組排序(通過返回值得到排序結(jié)果),例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"2",@"5",@"4",@"3",@"0",@"1",nil];
    
/**
NSSortDescriptor是用來指定排序規(guī)則, 對集合等進行排序時指定結(jié)果的排序規(guī)則;
他可以對一個類的某個屬性(下文中方法中的key參數(shù))指定排序規(guī)則, 即傳入字段的key。
可以在模型中將用來排序的字段key定義為一個常量。
也可以對一個字符串集合進指定排序規(guī)則, 這時, 只需要把參數(shù)key賦值為nil即可.
ascending : 是否升序, YES-升序, NO-降序.
*/

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:nil ascending:YES];
NSArray *sortArray = [NSArray arrayWithObjects:descriptor,nil];
NSArray *sortedArray = [mutableArray sortedArrayUsingDescriptors:sortArray];
    
NSLog(@"%@",sortedArray);

\color{red}{利用NSSortDescriptor直接對數(shù)組內(nèi)的元素進行排序,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"2",@"5",@"4",@"3",@"0",@"1",nil];
    
/**
NSSortDescriptor是用來指定排序規(guī)則, 對集合等進行排序時指定結(jié)果的排序規(guī)則;
他可以對一個類的某個屬性(下文中方法中的key參數(shù))指定排序規(guī)則, 即傳入字段的key。
可以在模型中將用來排序的字段key定義為一個常量。
也可以對一個字符串集合進指定排序規(guī)則, 這時, 只需要把參數(shù)key賦值為nil即可.
ascending : 是否升序, YES-升序, NO-降序.
*/
    
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:nil ascending:YES];
    
[mutableArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
    
NSLog(@"%@",mutableArray);

排序時如果key傳入錯誤,會拋出異常NSUnknownKeyException,可以這樣定義模型中要排序字段:

#import <Common/Common.h>

static NSString * const DAY = @"day";//在這里定義成常量,使用常量作為排序的key

@interface YSCResponseModelSignInRewardModel : JSONModel

@property (nonatomic, copy) NSString *points;//金幣
@property (nonatomic, copy) NSString *bonus;//紅包
@property (nonatomic, copy) NSString *day;//天數(shù),用來排序的字段

@end

冒泡排序

冒泡排序(Bubble Sort): 一種交換排序,它的基本思想是:兩兩比較相鄰的關(guān)鍵字,如果反序則交換,直到?jīng)]有反序的記錄為止

例如利用冒泡排序處理數(shù)據(jù)的代碼示例:

后臺提供的數(shù)據(jù)格式 :

截屏2020-07-13下午3.59.48.png

要求顯示的樣式 :

截屏2020-07-13下午4.14.16.png

未經(jīng)排序前的展示樣式:

截屏2020-07-13下午4.13.17.png

展示錯誤的代碼片段如下 :

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationItem.title = @"測試代碼控制器";
    
    NSDictionary *step_price = @{@"40-299" : @"5.00",@"≥300" : @"1.00",@"5-39" : @"6.00"};
    
    UILabel *goodsDescLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    goodsDescLabel.textColor = [UIColor blackColor];
    goodsDescLabel.numberOfLines = 0;
    goodsDescLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:goodsDescLabel];
    [goodsDescLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    
    __block NSString * goodsDescStr = @"";
    __block NSMutableArray * valueArray = [NSMutableArray array];
    
    [step_price enumerateKeysAndObjectsUsingBlock:^(NSString * key, NSString *  _Nonnull value, BOOL * _Nonnull stop) {
        
        goodsDescStr = [goodsDescStr stringByAppendingString:key];
        goodsDescStr = [goodsDescStr stringByAppendingString:@" 件"];
        NSString * valueStr = [NSString stringWithFormat:@"%@元",value];
        [valueArray addObject:valueStr];
        goodsDescStr = [goodsDescStr stringByAppendingString:[NSString stringWithFormat:@"%@\n",valueStr]];
        
    }];
    
    goodsDescStr = [goodsDescStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和換行字符
    NSMutableAttributedString *goodsDescString = [[NSMutableAttributedString alloc] initWithString:goodsDescStr];
    for (NSString * valueStr in valueArray) {
    [goodsDescString addAttribute:NSForegroundColorAttributeName value: [UIColor redColor] range:[goodsDescStr rangeOfString:valueStr]];
    }
    goodsDescLabel.attributedText = goodsDescString;
    
}

\color{red}{通過冒泡排序展示正確的代碼片段:}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationItem.title = @"測試代碼控制器";
    
    NSDictionary *step_price = @{@"40-299" : @"5.00",@"≥300" : @"1.00",@"5-39" : @"6.00"};
    
    UILabel *goodsDescLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    goodsDescLabel.textColor = [UIColor blackColor];
    goodsDescLabel.numberOfLines = 0;
    goodsDescLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:goodsDescLabel];
    [goodsDescLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    
    __block NSString * goodsDescStr = @"";
    __block NSMutableArray * valueArray = [NSMutableArray array];
    
    //獲取字典中所有的key
    NSArray *keyArray = step_price.allKeys;
    //對key進行排序
    NSMutableArray *sortedArray = [self sortKeyArray:keyArray];

    for (int i = 0; i < sortedArray.count; i++) {
        goodsDescStr = [goodsDescStr stringByAppendingString:sortedArray[i]];
        goodsDescStr = [goodsDescStr stringByAppendingString:@" 件"];
        NSString * valueStr = [NSString stringWithFormat:@"%@元",[step_price objectForKey:sortedArray[i]]];
        [valueArray addObject:valueStr];
        goodsDescStr = [goodsDescStr stringByAppendingString:[NSString stringWithFormat:@"%@\n",valueStr]];
    }
    
    goodsDescStr = [goodsDescStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和換行字符
    NSMutableAttributedString *goodsDescString = [[NSMutableAttributedString alloc] initWithString:goodsDescStr];
    for (NSString * valueStr in valueArray) {
    [goodsDescString addAttribute:NSForegroundColorAttributeName value: [UIColor redColor] range:[goodsDescStr rangeOfString:valueStr]];
    }
    goodsDescLabel.attributedText = goodsDescString;
    
}

///model.step_price中的key進行排序(冒泡排序)
- (NSMutableArray *)sortKeyArray:(NSArray *)keyArray{
    BOOL flag = YES;
    NSMutableArray * arr = keyArray.mutableCopy;
    
    for (int i = 0; i < arr.count && flag; i++) {
        flag = NO;
        for (int j = (int)arr.count-2; j >= i; j--) {
            if ([self handleKey:arr[j]] > [self handleKey:arr[j+1]]) {
                [arr exchangeObjectAtIndex:j withObjectAtIndex:j+1];
                flag = YES;
            }
        }
    }
    return arr;
}

///處理key
- (NSInteger)handleKey:(NSString *)key{
    NSString *newKey = nil;
    __block NSMutableString *mutableNewKey = [[NSMutableString alloc]init];
    if([key rangeOfString:@"-"].length){
        newKey = [key substringFromIndex:[key rangeOfString:@"-"].location + 1];
    }else{
        [key enumerateSubstringsInRange:NSMakeRange(0, key.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
            //使用正則表達式匹配數(shù)字
            NSError *error = nil;
            NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:@"(\\d+)" options:0 error:&error];
            if(!error && [expression matchesInString:substring options:0 range:NSMakeRange(0, substring.length)].count > 0) {
                [mutableNewKey appendString:substring];
            }
        }];
        newKey = [NSString stringWithFormat:@"%@",mutableNewKey];
    }
    return newKey.integerValue;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容