2014-02-10 24 views
0

我正在使用sortedArrayUsingSelector對我有的數組進行排序。sortedArrayUsingSelector caused SIGABRT

下面是我在呼喚它:

NSArray *sortedArray; 
SEL sel = @selector(intSortWithNum1:withNum2:withContext:); 
sortedArray = [_myObjs sortedArrayUsingSelector:sel]; 

而這裏的定義是:

- (NSInteger) intSortWithNum1:(id)num1 withNum2:(id)num2 withContext:(void *)context { 
    CLLocationCoordinate2D c1 = CLLocationCoordinate2DMake([((myObj *)num1) getLat], [((myObj *)num1) getLong]); 
    CLLocationCoordinate2D c2 = CLLocationCoordinate2DMake([((myObj *)num2) getLat], [((myObj *)num2) getLong]); 

    NSUInteger v1 = [self distanceFromCurrentLocation:(c1)]; 
    NSUInteger v2 = [self distanceFromCurrentLocation:(c2)]; 
    if (v1 < v2) 
     return NSOrderedAscending; 
    else if (v1 > v2) 
     return NSOrderedDescending; 
    else 
     return NSOrderedSame; 
} 

我得到我的主要的線程1 SIGABRT錯誤,當我跑我的應用程序。

任何想法?提前致謝。

注:我已經嘗試過這樣的:

NSArray *sortedArray = [[NSArray alloc] init]; 

它並沒有解決任何事情。

+1

你可以添加堆棧跟蹤嗎? * thread1 SIGABRT *不會說太多..(至少對我來說) – rdurand

+0

如何在XCode中獲取堆棧跟蹤? – Inbl

+0

在應用程序崩潰後的控制檯輸出中 – rdurand

回答

2

選擇器應該由被比較的對象來實現,並且應該只接受一個參數,它是另一個相同類型的對象。

例如,在NSArray中,有一個使用caseInsensitiveCompare比較字符串的示例。這是因爲NSString實現了caseInsensitiveCompare。

如果你想到它......怎麼能sortedArrayUsingSelector知道什麼作爲參數傳遞給你的例子中的函數?

編輯: 這意味着您用作'排序選擇器'的函數必須是由數組中的對象定義的函數。假設,如果你的數組中包含的人,你的陣列必須進行排序是這樣的:

sortedArray = [_myObjs sortedArrayUsingSelector:@selector(comparePerson:)]; 

的comparePerson消息將在您的陣列(人)在被髮送到對象,所以在你的人的類,你必須有一個名爲comparePerson功能:

- (NSComparisonResult)comparePerson:(Person *)person 
{ 
    if (self.age == person.age) 
     return NSOrderedSame; 
} 

在這個例子中,comparePerson本身(個體經營)與參數(人)進行比較,並認爲兩個人平等,如果他們有相同的年齡。正如你所看到的,這種比較和排序的方式可以非常強大,只要你編寫正確的邏輯。

+1

*「比較器消息發送給數組中的每個對象,並且其數組中有另一個對象作爲其單個參數。」*(來自https://developer.apple.com/library /ios/documentation/cocoa/reference/foundation/classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/sortedArrayUsingSelector :) – rdurand

+0

你是什麼意思的對象必須實現選擇器? 字面意思myObj應該是myObj實現選擇器? – Inbl

+1

請參閱編輯的回覆。 – Merlevede