標籤:objective oc 快速枚舉 數組排序
直接上代碼:
/* * 快速枚舉 * */ NSLog( @"++++++++++++++++++" ) ; NSArray *testArray = @[@1, @2, @3, @4, @5] ; //通過快速枚舉來遍曆數組元素 for (NSArray *object in testArray) { NSLog( @"%@", object ) ; } //不確定類型時用 id for ( id object in testArray ) { NSLog( @"%@", object ) ; } //快速遍曆集合 for ( id object in set1 ) { NSLog( @"%@", object ) ; } //快速遍曆字典(得到的是字典的鍵) //直接遍曆字典得到的是字典的每一個鍵,可以通過遍曆得到的鍵去擷取對應的值 for ( id object in dic1 ) { NSLog( @"%@", object ) ; } //dic1[key]可得到對應value,這是一個文法糖,相當於[dic1 objectForKey:key] for ( NSString *key in dic1) { NSLog( @"dictionary[%@]:%@", key, dic1[key] ) ; } /* * 數組排序 * */ //注意初始化數組時,所有數組元素對象的類型相同,如下會出錯:@[@1, @2, @"5", @3, @4] NSArray *array1 = @[@1, @2, @5, @3, @4] ; //使用數組排序方法對數組進行升序排序 NSArray *resultArray = [array1 sortedArrayUsingSelector:@selector(compare:)] ; NSLog( @"%@", resultArray ) ; Student *stu1 = [Student studentWithName:@"wang" score:@85] ; Student *stu2 = [Student studentWithName:@"zhen" score:@95] ; Student *stu3 = [Student studentWithName:@"gang" score:@65] ; NSMutableArray *stus = [NSMutableArray array] ; [stus addObject:stu1] ; [stus addObject:stu2] ; [stus addObject:stu3] ; [stus sortedArrayUsingSelector:@selector(scoreAscending:)] ; NSLog( @"%@", stus ) ; [stus sortedArrayUsingSelector:@selector(scoreDescending:)] ; NSLog( @"%@", stus ) ; [stus sortedArrayUsingSelector:@selector(nameAscending:)] ; NSLog( @"%@", stus ) ; [stus sortedArrayUsingSelector:@selector(nameDescending:)] ; NSLog( @"%@", stus ) ;
Objective-C----快速枚舉、數組排序