1 // 2 // main.m 3 // block的实际应用 4 // 5 // Created by LongMa on 15/9/2. 6 // Copyright (c) 2015年 Dast. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 #import "Countries.h" 11 int main(int argc, const char * argv[]) 12 { 13 char* countries[] = {"Uk","Korean","China","Japan","Autralia","Vietnam","Germany"}; 14 int length = sizeof(countries) / sizeof(countries[0]); 15 __block unsigned long num1; 16 __block unsigned long num2; 17 18 Countries *c1 = [Countries new]; 19 20 NSLog(@"国家名称按长度排序如下:"); 21 [c1 sortWithCountries:countries andLength: length withBlock:^BOOL(char *str1, char *str2) 22 { 23 num1 = strlen(str1); 24 num2 = strlen(str2); 25 26 //汗,放减法溢出,以后unsigned 类型做减法时,记得用int强转参与减法运算的数据。 27 return (int)num1 - (int)num2 > 0 ; 28 }]; 29 30 [c1 showCountries:countries WithLength:length]; 31 32 NSLog(@"国家名称按字典序排序如下:"); 33 [c1 sortWithCountries:countries andLength: length withBlock:^BOOL(char *str1, char *str2) 34 { 35 return strcmp(str1, str2) > 0; 36 }]; 37 [c1 showCountries:countries WithLength:length]; 38 39 return 0; 40 }
1 // 2 // Countries.h 3 4 #import <Foundation/Foundation.h> 5 typedef BOOL(^cmpBlock) (char*,char*); 6 @interface Countries : NSObject 7 - (void)sortWithCountries:(char*[])countries andLength:(int)length withBlock:(cmpBlock)cmpB; 8 - (void)showCountries:(char*[])countries WithLength:(int)length ; 9 @end
1 // 2 // Countries.m 3 4 #import "Countries.h" 5 #import <string.h>//别忘了 6 7 @implementation Countries 8 9 //char* 后面必须有[],是字符指针数组,不是字符指针,而(char*)[]是指向数组的指针,不对! cmpB:block变量,传入比较方法的代码 10 - (void)sortWithCountries:(char*[])countries andLength:(int)length withBlock:(cmpBlock)cmpB 11 { 12 for (int i = 0; i < length - 1; i++)//冒泡排序 13 { 14 for (int j = 0; j < length - 1 - i; j++) 15 { 16 //int res = strcmp(countries[j], countries[j + 1]);//在这换为block 17 BOOL res = cmpB(countries[j],countries[j + 1]);//block自定义的返回值为 BOOL 18 if (YES == res ) 19 { 20 char* temp = countries[j]; 21 countries[j] = countries[j + 1]; 22 countries[j +1] = temp; 23 } 24 } 25 } 26 } 27 28 - (void)showCountries:(char*[])countries WithLength:(int)length 29 { 30 for (int i = 0; i < length; i++) 31 { 32 NSLog(@"%s",countries[i]); 33 } 34 } 35 @end
运行结果如下:
ps:bug分析。unsigned long类型属性相减会溢出的问题,检查了好久,同桌和辅导员都没有解决!最后自己不断验证才发现是溢出了,
以后遇见这种情况,做减法前都 强转为int 保证负数能正常得出。并用 int类型 变量接收或 与0比较后 用BOOL类型变量接收 即可!
验证图如下:
时间: 2024-11-04 07:47:03