Objective-C的NSArray與NSMutableArray學習筆記

NSArray - 不可變數組

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

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

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

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

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

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

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

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

NSArray創建相關函數

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

\color{red}{通過簡單的方式創建數組,例如:}

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

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

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

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

+ (instancetype)array;

函數描述創建并返回空數組

返回值 : 空數組。

\color{red}{創建一個空數組,例如:}

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

函數描述創建并返回包含給定對象的數組

參數 :

anObject : 一個對象。

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

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

函數描述創建并返回包含參數列表中的對象的數組

參數:

firstObj : 數組的第一個對象。

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

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

\color{red}{通過指定對象創建數組,例如:}

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

函數描述創建并返回一個數組,該數組包含另一個給定數組中的對象

參數 :

array : 給定的數組。

返回值 : 包含數組中對象的數組。

\color{red}{通過指定數組創建數組(兩個數組內容的一樣),例如:}

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

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

參數 :

index : 數組邊界內的索引。

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

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

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

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

參數 :

indexes : 給定索引集。

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

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

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

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

參數 :

anObject : 一個對象。

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

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

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

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

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

參數 :

anObject : 要在數組中查找的對象。

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

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

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

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

參數 :

otherArray : 一個數組。

返回值 : 如果otherArray的內容等于調用方數組的內容,則為YES,否則為NO。

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

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

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

函數描述返回一個新數組,其中包含調用方數組中的元素,這些元素位于給定范圍指定的范圍內。如果range不在調用方數組的元素范圍內,則引發NSRangeException。

參數 :

range : 調用方數組中元素范圍內的范圍。

返回值 : 包含調用方數組元素的新數組,這些元素在范圍指定的范圍內。

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

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

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

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}{通過枚舉器遍歷}枚舉器是一種蘋果官方推薦的更加面向對象的一種遍歷方式,相比于for循環,它具有高度解耦、面向對象、使用方便等優勢。例如:

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向數組請求枚舉器
NSEnumerator *enumerator = [array7 objectEnumerator];
NSLog(@"%@",[enumerator allObjects]);

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

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

NSMutableArray - 可變數組

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

NSMutableArray創建相關函數

\color{red}{創建一個空數組,例如:}

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

\color{red}{通過指定對象創建數組,例如:}

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

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

參數 :

anObject : 要添加到數組內容末尾的對象。此值不能為nil。

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

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

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

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

參數 :

anObject : 要添加到數組內容的對象。此值不能為nil。如果對象為nil,則引發NSInvalidArgumentException。

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

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

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

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

參數 :

objects : 要插入到調用方數組中的對象數組。

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

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

    //不會越界
    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;

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

參數 :

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

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

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

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

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

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

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

參數 :

anObject : 要從數組中移除的對象。

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

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

函數描述清空數組中的所有元素

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

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

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

參數 :

indexes : 要從數組中移除的對象的索引。索引指定的位置必須在數組的邊界內。

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

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

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

- (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;

函數描述用一個對象替換索引處的對象

參數 :

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

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

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

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

參數 :

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

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

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

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);
//構造一個范圍的索引
indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
    
[mutableArray replaceObjectsAtIndexes:indexSet withObjects:mutableArray2];
    
NSLog(@"%@",mutableArray);
- (void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray<ObjectType> *)otherArray range:(NSRange)otherRange;

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

參數 :

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

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

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

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

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

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

參數 :

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;

函數描述將調用方數組的元素設置為其他給定數組中的元素

參數 :

otherArray : 用來替換調用方數組內容的對象數組。

\color{red}{設置數組元素,例如 :}

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));

函數描述使用給定NSComparator塊指定的比較方法對調用方數組排序

參數 :

cmptr :比較器塊。

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

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

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進行數組排序(通過返回值得到排序結果),例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"2",@"5",@"4",@"3",@"0",@"1",nil];
    
/**
NSSortDescriptor是用來指定排序規則, 對集合等進行排序時指定結果的排序規則;
他可以對一個類的某個屬性(下文中方法中的key參數)指定排序規則, 即傳入字段的key。
可以在模型中將用來排序的字段key定義為一個常量。
也可以對一個字符串集合進指定排序規則, 這時, 只需要把參數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直接對數組內的元素進行排序,例如:}

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"2",@"5",@"4",@"3",@"0",@"1",nil];
    
/**
NSSortDescriptor是用來指定排序規則, 對集合等進行排序時指定結果的排序規則;
他可以對一個類的某個屬性(下文中方法中的key參數)指定排序規則, 即傳入字段的key。
可以在模型中將用來排序的字段key定義為一個常量。
也可以對一個字符串集合進指定排序規則, 這時, 只需要把參數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;//天數,用來排序的字段

@end

冒泡排序

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

例如利用冒泡排序處理數據的代碼示例:

后臺提供的數據格式 :

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

要求顯示的樣式 :

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

未經排序前的展示樣式:

截屏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) {
            //使用正則表達式匹配數字
            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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內容