2012-03-26 86 views
0

我有一個數組unsortedPosts滿字典,它看起來是這樣的,如果我在終端內容打印出來NSDictionaries的NSArray的:排序使用NSSortDescriptor不工作

{ 
    "created_at" = 1332584959; 
    id = "61926802418418"; 
    network = "net1"; 
    text = "text1"; 
    url = "https://www.google.com"; 
}, 
{ 
    "created_at" = 1332581096; 
    id = "6192689218418"; 
    network = "net1"; 
    text = "text1"; 
    url = "https://www.yahoo.com"; 
}, 
{ 
    "created_at" = 1332581074; 
    id = "6192688628418"; 
    network = "net1"; 
    text = "text1"; 
    url = "https://www.aol.com"; 
} 

我想通過created_at場對它們進行排序(unix時間戳)。我正在使用NSSortDescriptor,如下所示:

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"\"created_at\"" ascending:TRUE]; 
NSMutableArray *sortDescriptors = [NSMutableArray arrayWithObject:sortDescriptor]; 
NSArray *sortedSocialPosts; 
sortedSocialPosts = [unsortedSocialPosts sortedArrayUsingDescriptors:sortDescriptors]; 

但輸出未排序。

編輯

我試圖運行它,而無需使用周圍created_at轉義引號(每@Eimantas答案):

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"created_at" ascending:TRUE]; 
NSMutableArray *sortDescriptors = [NSMutableArray arrayWithObject:sortDescriptor]; 
NSArray *sortedSocialPosts; 
sortedSocialPosts = [unsortedSocialPosts sortedArrayUsingDescriptors:sortDescriptors]; 

但我得到這個錯誤:

-[__NSCFNumber length]: unrecognized selector sent to instance 0x6a2a3c0 
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0x6a2a3c0' 
+0

如果陣列印有'的NSLog()''周圍的created_at'報價只是呈現方式的神器吧打印的東西 - 很可能是因爲下劃線的 – JeremyP 2012-03-26 08:18:00

回答

3

你不需要逃脫的報價,只需通過@"created_at",你就會很好。有時會在打NSLog()調用時打印報價。我非常肯定,您只需訪問@"created_at"密鑰和valueForKey:方法即可訪問創建時間戳。

更新

這可能意味着一些created_at值可能是NSString實例和一些 - NSNumber實例。你能否確認所有的created_at值是同一類型的? (使用NSLog(@"%@", [[unsortedSocialPosts valueForKey:@"created_at"] valueForKey:@"class"]);

+0

看到編輯上面;去掉引號給我一個錯誤。 – sepiroth 2012-03-26 14:04:47

+0

好的呼叫;一個完全是一個字符串:) – sepiroth 2012-03-26 17:49:34