#import <Foundation/Foundation.h>數組
//定義⼀一個block,返回值爲BOOL,有兩個NSString參數。實現:判spa
//斷字符串是否相等。排序
BOOL (^compareString)(NSString *, NSString *) = ^(NSString *str1, NSString *str2){字符串
if ([str1 isEqualToString:str2]) {string
return YES;it
}else{io
return NO;table
}import
};語法
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);
//4. 使用Block根據Person的age進行排序,並輸出
[array sortUsingComparator:^NSComparisonResult(Person *p1 ,Person *p2){
if([p1 age] > [p2 age])
return NSOrderedDescending;
else
return NSOrderedSame;
}];
/*
//根據年齡 升序排列
[array sortUsingComparator:^NSComparisonResult(id p1, id p2){
if ([p1 age] > [p2 age]) { // <:降序. >:升序
return NSOrderedDescending;
}
return NSOrderedSame;
}];
*/