2010-01-09 11 views

cevap

16

Sen onlar da intValue yöntemine sahip olarak çok NSStrings için sorunsuz çalışır sortedArrayUsingFunction:context: yöntemi için verilen örnek kodu kullanabilirsiniz.

// Place this functions somewhere above @implementation 
static NSInteger intSort(id num1, id num2, void *context) 
{ 
    int v1 = [num1 intValue]; 
    int v2 = [num2 intValue]; 
    if (v1 < v2) 
     return NSOrderedAscending; 
    else if (v1 > v2) 
     return NSOrderedDescending; 
    else 
     return NSOrderedSame; 
} 

// And used like this 
NSArray *sortedArray; 
sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL]; 
+0

+1 Sadece bu hat ile intSort gövdesini değiştirebilirsiniz: return [(NSString *) num1 karşılaştırmak: num2 seçenekleri: NSNumericSearch]; – gerry3

+0

@ gerry3 Elbette, apple.com'da verilen örnek kodu çektim. – epatel

6

Nesneleriniz sayı olduğundan, NSString nesneleri kullanmak yerine, NSNumber nesnelerini kullanabilirsiniz (stringValue özelliği aracılığıyla kolayca dizelere dönüştürülebilir) ve diziyi sortedArrayUsingDescriptors: kullanarak sıralayabilirsiniz. Örneğin

:

NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES]; 
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil]; 
[sorter release]; 
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:sorters]; 
[sorters release]; 
İlgili konular