Translate

顯示具有 NSArray 標籤的文章。 顯示所有文章
顯示具有 NSArray 標籤的文章。 顯示所有文章

2012年9月25日 星期二

NSArray compare 排序

其實一般NSArray的排序

NSArray *sortedArray = [temp_dic_dic sortedArrayUsingSelector:@selector(compare:)]; for(int i =0; i < [sortedArray count]; i++) { int x = [[sortedArray objectAtIndex:i] intValue]; NSLog(@"x is %d",x); }

但是我需要的是針對NSArray多個dictionary,每個dictionary都有個key值為"dddNumber",key值的形態為字串,如何依照NSString比對呢?

NSMutableArray *array = [[NSMutableArray alloc] init]; for (int i = 0; i < 10; i ++) { NSDictionary *aDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"akdj%i", i], @"phaseNumber", nil]; [array addObject:aDict]; [aDict release]; } // 排序 NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"dddNumber" ascending:YES] autorelease]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];
是要用intValue排序的话。上面代码是不对的,上面是按照String来排序的。 如果要按照intValue排序,参见如下:

方法
NSComparisonResult compare(NSDictionary *firstDict, NSDictionary *secondDict, void *context) {NSLog(@"IN(%i, %i)", [[firstDict objectForKey:@"ddd"] intValue], [[secondDict objectForKey:@"ddd"] intValue]); if ([[firstDict objectForKey:@"ddd"] intValue] < [[secondDict objectForKey:@"ddd"] intValue]) return NSOrderedAscending; else if ([[firstDict objectForKey:@"ddd"] intValue] > [[secondDict objectForKey:@"ddd"] intValue]) return NSOrderedDescending; else return NSOrderedSame; } [array sortUsingFunction:compare context:NULL];
使用
[array sortUsingFunction:compare context:NULL];

2012年6月15日 星期五

NSArray to NSString

从字符串分割到数组- componentsSeparatedByString: NSString *string = [[NSString alloc] initWithString:@"One,Two,Three,Four"]; NSLog(@"string:%@",string);
 NSArray *array = [string componentsSeparatedByString:@","];
 NSLog(@"array:%@",array); [string release]; 結果呈現 2012-06-15 17:10:34.028 Hotairballoon[546:707] string:One,Two,Three,Four 2012-06-15 17:10:34.029 Hotairballoon[546:707] array:( One, Two, Three, Four ) 从数组合并元素到字符串- componentsJoinedByString: NSArray *array = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",nil]; NSString *string = [array componentsJoinedByString:@","];
 NSLog(@"string:%@",string); 結果呈現 2012-06-15 17:16:57.596 Hotairballoon[565:707] string:One,Two,Three,Four