![](/img/trans.png)
[英]Sorting array(NSString + Number) using NSSortDescriptor in IOS?
[英]Sorting array of wrapper objects in iOS using NSSortDescriptor
我正在嘗試對UserWrapper對象數組進行排序。 包裝對象包含對象User,而User對象包含屬性UserName(我要根據其排序)。
對用戶數組( 源 )進行排序很容易,但是添加的UserWrapper層使我的事情變得復雜。 請幫助!
這是我的代碼,適用於簡單的User數組:
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"UserName"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)] ;
NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor];
NSMutableArray *contactsStartingWithKey = [nameIndexesDictionary objectForKey:aKey];
[contactsStartingWithKey sortUsingDescriptors:descriptors]; // Exception thrown here because UserName is not a property of UserWrapper, but of UserWrapper.User
在您的情況下,排序描述符的key參數也可以通過key path設置 :
[[NSSortDescriptor alloc] initWithKey:@"User.UserName"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)] ;
盡管NSSortDescriptor
的API和文檔有點不一致,但是“ key”參數實際上是密鑰路徑。 因此,您只需指定@"User.UserName"
作為鍵,您的代碼就可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.