NSMutableArray 排序 --- 三种方法

来源:互联网 发布:淘宝怎么查付款顺序 编辑:程序博客网 时间:2024/06/03 12:05
 

(1)直接调用系统的方法排序int

NSMutableArray*array = [[NSMutableArrayalloc]init];

[arrayaddObject:[NSNumbernumberWithInt:20]];

[arrayaddObject:[NSNumbernumberWithInt:1]];

[arrayaddObject:[NSNumbernumberWithInt:4]];

NSArray*sortedArray = [arraysortedArrayUsingSelector:@selector(compare:)];

for(inti =0; i < [sortedArraycount]; i++)

{

intx = [[sortedArrayobjectAtIndex:i]intValue];

NSLog(@"######%d\n", x);

}


(2)用descriptor方法

#import<Cocoa/Cocoa.h>

@interfaceNode: NSObject {

intx;

inty;

intv;

}

@property intx;

@property inty;

@property intv;

- (id)init:(int)tx y:(int)ty v:(int)tv;

@end

@implementationNode

@synthesizex;

@synthesizey;

@synthesizev;

- (id)init:(int)tx y:(int)ty v:(int)tv {

x= tx;

y= ty;

v= tv;

return self;

}

@end

intmain(intargc,char*argv[])

{

NSMutableArray *myMutableArray = [[NSMutableArrayalloc]init];

Node *n[2];

n[0] = [[Nodealloc]init:2y:1v:1];

n[1] = [[Nodealloc]init:4y:2v:2];

[myMutableArrayaddObject:n[0]];

[myMutableArrayaddObject:n[1]];

NSSortDescriptor* sortByA = [NSSortDescriptorsortDescriptorWithKey:@"x"ascending:NO];

[myMutableArraysortUsingDescriptors:[NSArrayarrayWithObject:sortByA]];

for(Node*tinmyMutableArray) {

NSLog(@"x === %d", t.x);

NSLog(@"y === %d", t.y);

NSLog(@"v === %d", t.v);

}

}

(3)自定义重写方法

/*

Abstract:Constants returned by comparison functions, indicating whether a value is equal to, less than, or greater than another value.

Declaration:enumCFComparisonResult{

kCFCompareLessThan= -1,

kCFCompareEqualTo= 0,

kCFCompareGreaterThan= 1

};

*/

#import<Cocoa/Cocoa.h>

@implementation NSNumber (MySort)

- (NSComparisonResult) myCompare:(NSString *)other {

//这里可以作适当的修正后再比较

int result = ([selfintValue]>>1) - ([other intValue]>>1);

//这里可以控制排序的顺序和逆序

return result < 0 ?NSOrderedDescending : result >0 ?NSOrderedAscending :NSOrderedSame;

}

@end

int main(int argc, char *argv[])

{

NSMutableArray *array = [[NSMutableArrayalloc]init];

[arrayaddObject:[NSNumbernumberWithInt:20]];

[arrayaddObject:[NSNumbernumberWithInt:1]];

[arrayaddObject:[NSNumbernumberWithInt:4]];

NSArray *sortedArray = [arraysortedArrayUsingSelector:@selector(myCompare:)];

for(int i = 0; i < [sortedArraycount]; i++)

{

int x = [[sortedArrayobjectAtIndex:i]intValue];

NSLog(@"######%d\n", x);

}

}

 

http://hi.baidu.com/popln/blog/item/4b16c3ae918df0d97cd92ae3.html

原创粉丝点击