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中使用數組文字語法來創建包含給定對象的數組:
//空數組
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;
函數描述 :創建并返回空數組。
返回值 : 空數組。
NSArray *array = [[NSArray alloc] init];
NSArray *array2 = [NSArray array];
+ (instancetype)arrayWithObject:(ObjectType)anObject;
函數描述 :創建并返回包含給定對象的數組。
參數 :
anObject : 一個對象。
返回值 :包含單個元素對象的數組。
+ (instancetype)arrayWithObjects:(ObjectType)firstObj, ... NS_REQUIRES_NIL_TERMINATION;
函數描述 :創建并返回包含參數列表中的對象的數組。
參數:
firstObj : 數組的第一個對象。
... : 逗號分隔的附加對象列表,以nil結尾。
返回值 : 包含參數列表中對象的數組。
//只有一個元素
NSArray *array3 = [NSArray arrayWithObject:@"aaa"];
//有n個元素
NSArray *array4 = [NSArray arrayWithObjects:@"1111",@"2222",@"333", nil];
+ (instancetype)arrayWithArray:(NSArray<ObjectType> *)array;
函數描述 :創建并返回一個數組,該數組包含另一個給定數組中的對象。
參數 :
array : 給定的數組。
返回值 : 包含數組中對象的數組。
NSArray *array5 = [NSArray arrayWithArray:array4];
NSArray操作相關函數
- (ObjectType)objectAtIndex:(NSUInteger)index;
函數描述 :返回位于指定索引處的對象。如果索引超出數組末尾(即,如果索引大于或等于計數返回的值),則會引發NSRangeException。
參數 :
index : 數組邊界內的索引。
返回值 : 位于索引處的對象。
[array7 objectAtIndex:下標];
//簡單取值
array7[下標];
- (NSArray<ObjectType> *)objectsAtIndexes:(NSIndexSet *)indexes;
函數描述 :返回一個數組,該數組中的對象位于給定索引集指定的索引處。返回的對象按照索引中索引的升序排列,因此索引中索引較高的返回數組中的對象將跟隨索引中索引較小的對象。如果索引中的任何位置超出了數組的界限,則引發NSRangeException,索引為nil。
參數 :
indexes : 給定索引集。
返回值 :在索引指定的索引處包含數組中的對象的數組。
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。
[array7 indexOfObject:要找的對象]
- (BOOL)containsObject:(ObjectType)anObject;
函數描述 :返回一個布爾值,該值指示給定對象是否存在于數組中。從索引0開始,檢查數組中的每個元素是否與對象相等,直到找到匹配項或到達數組的結尾。如果isEqual:返回YES,則視為對象相等。
要確定數組是否包含對象的特定實例,可以通過調用indexOfObjectIdenticalTo:方法并將返回值與NSNotFound進行比較來測試標識而不是相等性。
參數 :
anObject : 要在數組中查找的對象。
返回值 : 如果數組中有對象,則為YES,否則為NO。
[array7 containsObject:要查找的對象]
- (BOOL)isEqualToArray:(NSArray<ObjectType> *)otherArray;
函數描述 : 將調用方數組與另一個數組進行比較。如果兩個數組各自擁有相同數量的對象,并且每個數組中的給定索引處的對象滿足isEqual:test,則兩個數組具有相同的內容。
參數 :
otherArray : 一個數組。
返回值 : 如果otherArray的內容等于調用方數組的內容,則為YES,否則為NO。
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 : 調用方數組中元素范圍內的范圍。
返回值 : 包含調用方數組元素的新數組,這些元素在范圍指定的范圍內。
NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
NSRange range = NSMakeRange(0, 2);
NSLog(@"%@", [array7 subarrayWithRange:range]);
NSArray數組的遍歷
NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
for (int i = 0 ; i < array7.count; i++){
NSLog(@"%@",array7[I]);
}
NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
for (NSString *str in array7) {
NSLog(@"%@",str);
}
,枚舉器是一種蘋果官方推薦的更加面向對象的一種遍歷方式,相比于for循環,它具有高度解耦、面向對象、使用方便等優勢。例如:
NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
[array7 enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",array7[idx]);
}];
NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
//通過objectEnumerator向數組請求枚舉器
NSEnumerator *enumerator = [array7 objectEnumerator];
NSLog(@"%@",[enumerator allObjects]);
NSArray *array7 = @[@"111",@"222",@"333",@"444",@"555",@"666"];
//通過reverseObjectEnumerator向數組請求枚舉器
NSEnumerator *enumerator = [array7 reverseObjectEnumerator];
NSLog(@"%@",[enumerator allObjects]);
NSMutableArray - 可變數組
NSMutableArray,可變數組,是NSArray的子類,可以對數組進行加入、刪除或者替換元素,使用比NSArray更加方便,但缺少了NSArray的安全性。
NSMutableArray創建相關函數
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
NSMutableArray *mutableArray2 = [NSMutableArray array];
//只有一個元素
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。
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。
NSMutableArray *mutableArray = [NSMutableArray arrayWithObject:@"111"];
[mutableArray insertObject:@"333" atIndex:0];
NSLog(@"%@",mutableArray);
- (void)insertObjects:(NSArray<ObjectType> *)objects atIndexes:(NSIndexSet *)indexes;
函數描述 :將提供數組中的對象插入到調用方數組中的指定索引處。在前面的插入之后,對象中的每個對象依次插入到調用方數組的索引中指定的相應位置。
參數 :
objects : 要插入到調用方數組中的對象數組。
indexes :對象中的對象應插入的索引。索引中的位置計數必須等于對象計數。
//不會越界
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。
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
[mutableArray removeObjectAtIndex:1];
NSLog(@"%@",mutableArray);
- (void)removeLastObject;
函數描述 :刪除數組中索引值最高的對象。
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
[mutableArray removeLastObject];
NSLog(@"%@",mutableArray);
- (void)removeObject:(ObjectType)anObject;
函數描述 :刪除給定對象數組中的所有引用。此方法通過使用isEqual:方法將對象與調用方數組中的對象進行比較來確定匹配。如果數組不包含對象,則該方法無效。
參數 :
anObject : 要從數組中移除的對象。
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
[mutableArray removeObject:@"222"];
NSLog(@"%@",mutableArray);
- (void)removeAllObjects;
函數描述 :清空數組中的所有元素。
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
[mutableArray removeAllObjects];
NSLog(@"%@",mutableArray);
- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes;
函數描述 :從數組中刪除指定索引處的對象。此方法類似于removeObjectAtIndex:,但允許您通過一個操作有效地刪除多個對象。如果索引為nil,則此方法引發異常。
參數 :
indexes : 要從數組中移除的對象的索引。索引指定的位置必須在數組的邊界內。
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);
- (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);
}
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(ObjectType)anObject;
函數描述 :用一個對象替換索引處的對象。
參數 :
index : 要替換的對象的索引。此值不能超過數組的邊界。如果索引超出數組末尾,則引發NSRangeException。
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 : 在由索引指定的索引處替換調用方數組中對象的對象。索引中的位置計數必須等于對象計數。
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中的對象。
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處替換對象的對象的索引。
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1111",@"222",@"333", nil];
[mutableArray exchangeObjectAtIndex:0 withObjectAtIndex:2];
NSLog(@"%@",mutableArray);
- (void)setArray:(NSArray<ObjectType> *)otherArray;
函數描述 :將調用方數組的元素設置為其他給定數組中的元素。
參數 :
otherArray : 用來替換調用方數組內容的對象數組。
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 :比較器塊。
//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);
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);
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): 一種交換排序,它的基本思想是:兩兩比較相鄰的關鍵字,如果反序則交換,直到沒有反序的記錄為止。
例如利用冒泡排序處理數據的代碼示例:
后臺提供的數據格式 :
要求顯示的樣式 :
未經排序前的展示樣式:
展示錯誤的代碼片段如下 :
- (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;
}
- (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;
}