用category重写NSMutableArray排序,倒序
首先新建Category为convert Category on为NSMutableArray的工程
可以看见.h的文件名为NSMutableArray+convert.h
.m 文件名为NSMutableArray+convert.m
NSMutableArray+convert.h文件的写法是
#import<Foundation/Foundation.h>@interfaceNSMutableArray(convert)-(NSMutableArray*)convert:(NSMutableArray*)array;-(NSArray*)convert1:(NSArray*)array;-(NSMutableArray*)convert2:(NSMutableArray*)array;@end
NSMutableArray+convert.h文件的写法是
#import"NSMutableArray+convert.h"@implementationNSMutableArray(convert)-(NSMutableArray*)convert:(NSMutableArray*)array{NSIntegercount=[arraycount];for(inti=0;i<count;i++){for(intj=0;j<count-i-1;j++){//if([[arrayobjectAtIndex:j]intValue]>[[arrayobjectAtIndex:(j+1)]intValue]){//if([[arrayobjectAtIndex:j]compare:[arrayobjectAtIndex:j+1]]==-1){if([[arrayobjectAtIndex:j]compare:[arrayobjectAtIndex:j+1]options:NSNumericSearch]==-1){//potionsNSNumericSearch=64,[arrayexchangeObjectAtIndex:jwithObjectAtIndex:(j+1)];}}}for(NSString*iinarray){NSLog(@"冒泡排序降序:%@",i);}returnarray;}-(NSArray*)convert1:(NSArray*)array{//NSIntegercount=[arraycount];array=[[arrayreverseObjectEnumerator]allObjects];//数组倒叙排列for(NSString*iinarray){NSLog(@"数组倒叙输出,用方法%@",i);}returnarray;}-(NSMutableArray*)convert2:(NSMutableArray*)array{NSIntegercount=[arraycount];for(intj=0;j<count/2;j++){//if([[arrayobjectAtIndex:j]intValue]>[[arrayobjectAtIndex:(j+1)]intValue]){//if([[arrayobjectAtIndex:j]compare:[arrayobjectAtIndex:j+1]]==-1){//if([[arrayobjectAtIndex:i]compare:[arrayobjectAtIndex:j+1]options:NSNumericSearch]==-1){//potionsNSNumericSearch=64,[arrayexchangeObjectAtIndex:jwithObjectAtIndex:(count-j-1)];}for(NSString*iinarray){NSLog(@"数组倒序输出,交换位置%@",i);}returnarray;}@end
main.m文件中代码
#import<Foundation/Foundation.h>#import"NSMutableArray+convert.h"intmain(intargc,constchar*argv[]){@autoreleasepool{NSMutableArray*array=[NSMutableArrayarrayWithObjects:@"34",@"8",@"32",@"90",@"33",@"78",@"30",nil];[arrayconvert:array];NSMutableArray*array1=[NSMutableArrayarrayWithObjects:@"34",@"8",@"32",@"90",@"33",@"78",@"30",nil];[array1convert1:array1];NSMutableArray*array2=[NSMutableArrayarrayWithObjects:@"34",@"8",@"32",@"90",@"33",@"78",@"30",nil];[array2convert2:array2];}return0;}
类目Category
Category也叫分类或类目
主要作用是为没有源代码的类添加方法。
通过Category添加的方法会成为原类的一部分。从而达到扩展一 类的功能。
Category的定义
新建文件
选择Objective-C Category模板
填写类名和分类名
.h文件添加方法声明
.m添加方法实现
需要使用的地方进行调用。
Category的声明
NSString+SayHi.h文件
@interface NSString (SayHi)
- (void)hi;
@end
Category的实现
NSString+SayHi.m文件
#import“NSString+SayHi.h”
@implementation NSString(SayHi)
- (void)hi{
NSLog(@”这是通过category为NSString添加的hi方法”);
}
@end
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。