标签:排序
什么时候block需要作为方法的参数.
block可以作为函数、方法的返回值
. block与函数的异同
. 相同点: 都可以封装1段代码在其中.
. 不同点:
. block是1个数据类型. 而函数就是函数.
. block可以作为函数的参数传递。而函数不能直接作为参数传递.
. block可以嵌套.函数不能嵌套定义.
ZYArray.h
#import <Foundation/Foundation.h>
typedef BOOL (^SortArray)(char *countries1,char *countries2);
@interface ZYArray : NSObject
- (void)sortWithArray:(char *[])array andLength:(int)length andBlcok:(SortArray)sortArray;
@end
ZYArray.m
#import "ZYArray.h"
@implementation ZYArray
- (void)sortWithArray:(char *[])array andLength:(int)length andBlcok:(SortArray)sortArray
{
for (int i = 0 ; i<length - 1; i++)
{
for (int j = 0 ; j<length - i -1; j++)
{
BOOL res = sortArray(array[j],array[j+1]);
if (res >0)
{
char *temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for (int i = 0 ; i<length ; i++)
{
NSLog(@"%s",array[i]);
}
}
@end
main.m
#import <Foundation/Foundation.h>
#import "ZYArray.h"
int main(int argc, const char * argv[])
{
char *countries[] =
{
"Nepal",
"Cambodia",
"Afghanistan",
"China",
"Singapore",
"Bangladesh",
"India",
"Maldives",
"South Korea",
"Bhutan",
"Japan",
"Sikkim",
"Sri Lanka",
"Burma",
"North Korea",
"Laos",
"Malaysia",
"Indonesia",
"Turkey",
"Mongolia",
"Pakistan",
"Philippines",
"Vietnam",
"Palestine"
};
int length = sizeof(countries)/sizeof(countries[0]);
ZYArray *array = [[ZYArray alloc]init];
[array sortWithArray:countries andLength:length andBlcok:^BOOL(char *countries1, char *countries2) {
return strcmp(countries1, countries2);
}];
return 0;
}
这里是按照首字母排序 当然还可以按照别的方式进行排序 看各位的需求
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:排序
原文地址:http://blog.csdn.net/yi_zz32/article/details/48845233