我有一個是獲取所謂的「播放器」的實體NSFetchRequest和我想要的結果通過以下順序3個屬性進行排序:核心數據和NSSortDescriptor根據基於NSString的
- 名爲「sendingoffOffence」的屬性是否爲零
- 「team.homeMatch」實體中的關係是否爲零
- 我希望按照升序對「number」屬性中的字符串進行排序。
基本上,我希望讓所有有紅牌的球員(「發送保證」不是零)出現在名單的頂部,然後根據球員是否在家然後最終讓一組球員進入一個進攻組,根據他們的球衣號碼排序。
因此,我用下面的代碼在我的讀取請求:
// Set the entity for the fetch request
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Player"
inManagedObjectContext:self.match.managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"match == %@", self.match];
[fetchRequest setPredicate:predicate];
// Sort the results
// Sort according to whether the user has a red card/sendingOffOffence
NSSortDescriptor *hasRedCard = [[NSSortDescriptor alloc] initWithKey:@"sendingoffOffence" ascending:NO];
// Sort according to whether the user is on the home team or not
NSSortDescriptor *isHomeTeam = [[NSSortDescriptor alloc] initWithKey:@"team.homeMatch" ascending:NO];
// Sort according to the player's jersey numbers
NSSortDescriptor *number = [[NSSortDescriptor alloc] initWithKey:@"number" ascending:YES selector:@selector(localizedStandardCompare:)];
[fetchRequest setSortDescriptors:@[hasRedCard, isHomeTeam, number]];
// Set the amount of records to retrieve from the database
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:self.match.managedObjectContext
sectionNameKeyPath:nil
cacheName:@"MatchCache"]
然而,當我執行上面的代碼,我得到如下結果:
這個排序順序是錯誤的,因爲我想要下列命令出現在紅卡部分:
- 11 - 首頁
- 12 - 首頁
- 0 - 客場
- 11 - 客場
- 21 - 客場
而在黃牌部分:
- 1 - 首頁
- 2 - 首頁
- 99 - 首頁
- 1 - 客場
- 31 - 客場
看起來正確黃牌部分排序,但紅牌部分顯示效果非常怪異的行爲,使得它看起來,這是不根本不需要排序。
我相當難過,爲什麼紅卡部分無法正確排序 - 任何想法?我應該在內存中排序這些對象,而不是依靠核心數據來獲得我的首選訂單嗎?
請注意,這是一個具有SQL支持持久性存儲的核心數據應用程序。
UPDATE
以下是SQL語句的核心數據在使用我取:
CoreData: annotation: fetch using NSSQLiteStatement <0x11c77cd0> on entity 'SPlayer' with
sql text 'SELECT t0.Z_ENT, t0.Z_PK FROM ZFSMANAGEDOBJECT t0 LEFT OUTER JOIN ZSTEAM t1 ON
t0.ZTEAM = t1.Z_PK WHERE (t0.ZMATCH1 = ? AND t0.Z_ENT = ?) ORDER BY
t0.ZSENDINGOFFOFFENCE DESC, t1.ZHOMEMATCH DESC, t0.ZNUMBER COLLATE NSCollateFinderlike '
[上SQL調試打開(http://stackoverflow.com/questions/6428630/xcode4-and-core-data-how -to-enable-sql-debugging),並確保它生成你期望的SQL。除了它發送的SQL之外,您可以打開調試級別以使其記錄它正在接收的數據。 –
是否保存了您的託管對象上下文?你確定你的標籤不只是不正確的顯示? – Sulthan
我打開了SQL調試並添加了上面的SQL命令。我沒有正確顯示項目,因爲我的FetchedResultsController中的數組是沒有正確排序的東西。 – linusthe3rd