2016年5月31日 星期二

NSDictionary排序實作

原先按照以往的開發習慣(C#)將一些設定寫入NSDictionary,取值時才注意到原來NSDictionary是沒有排序的...

stackoverflow真是開發人員的好朋友,

參考到這篇Sorting NSArray of dictionaries by value of a key in the dictionaries

才發現又犯了老毛病用C#再看待iOS專案...

在iOS Developer Library中,有一個專門講述排序的主題<<Sort Descriptor Programming Topics>>

還想進一步鑽研的話,還有一篇Key-Value Coding Programming Guide

----
NSDictionary排序實作如下:


NSDictionary *dataDictionary = [NSDictionary alloc] initWith......;

NSSortDescriptor *keyDescriptor = [[NSSortDescriptor alloc] initWithKey:@"key" ascending: YES]; //ascending:NO為降冪排序

NSArray *sortdescriptors = [NSArray arrayWithObject:keyDescriptor];

NSMutableArray *sortedarray = [[NSMutableArray alloc] initWithArray: [dataDictionary.allValues sortedArrayUsingDescriptors: sortdescriptors]];

沒有留言:

張貼留言