首页 > 代码库 > block 数组排序
block 数组排序
//
// main.m
// Block作业
//
// Created by lanou3g on 14-11-20.
// Copyright (c) 2014年 Lanou_zhou. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
//定义?一个block,返回值为BOOL,有两个NSString参数。实现:判
//断字符串是否相等。
BOOL (^compareString)(NSString *, NSString *) = ^(NSString *str1, NSString *str2){
if ([str1 isEqualToString:str2]) {
return YES;
}else{
return NO;
}
};
if (compareString(@"sss",@"sss")) {
NSLog(@"相同");
}
//定义?一个block,返回值为NSInteger,有两个参数,?一个是 NSArray,?一个是NSString。实现:判断数组时候包含此字符串,如 果包含,返回字符串的下标,如果不包括,返回-1。
NSArray *arr = @[@"aa",@"ss",@"ww"];
NSString *str = @"ss";
int (^find)(NSArray *, NSString *) = ^(NSArray *arr, NSString *str ){
for (int i = 0; i < arr.count; i++) {
if ([arr[i] isEqualToString:str]) {
return i;
}
}
return -1;
};
int f = find(arr,str);
NSLog(@"%d",f);
//创建?一个数组,初始化为@“123",@"21",@"33",@"69", @“108”,
//@“256”。使?用Block语法,进?行数组的排序。并输出内容。 排序结果:108 123 21 256 33 69
//提?示:sortedArrayWithOptions:usingComparator:
//不可变数组
NSArray *arr1 = @[@"23", @"1", @"3", @"2", @"108"];
NSArray *arr2 = [arr1 sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
if ([obj1 intValue] > [obj2 intValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
];
NSLog(@"sortArray1:%@", arr2);
NSArray *arr11 = @[@"23", @"1", @"3", @"2", @"108"];
NSArray *a1 = [arr11 sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
if ([obj1 intValue] > [obj2 intValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
];
NSLog(@"sortArray1:%@", a1);
//5, 给可变数组排序的block
//5,1
NSComparator sortBlock = ^(id string1, id string2)
{
return [string1 compare:string2];
};
NSMutableArray *stringArray = [NSMutableArray arrayWithObjects:@"g", @"c", @"b", @"a",nil];
NSArray *a = [stringArray sortedArrayUsingComparator:sortBlock];
NSLog(@"Array:%@", a);
//分开写的block 不可变数组
NSComparator sortBlock1 = ^(id string1, id string2)
{
return [string1 compare:string2];
};
NSArray *stringArray2 = [NSArray arrayWithObjects:@"g", @"c", @"b", @"a",nil];
NSArray *a2 = [stringArray2 sortedArrayUsingComparator:sortBlock1];
NSLog(@"分开写的block 可变数组:%@", a2);
return 0;
}
block 数组排序