从plist文件中排列数组
问题描述:
我有一个包含字典的自定义plist文件。每个字典包含一个汽车信息:从plist文件中排列数组
<key>Ford</key>
<dict>
<key>name</key>
<string>Ford</string>
<key>color</key>
<string>green</string>
<key>price</key>
<integer>45000</integer>
</dict
<key>Toyota</key>
<dict>
<key>name</key>
<string>Toyota</string>
<key>color</key>
<string>blue</string>
<key>price</key>
<integer>40000</integer>
</dict
<key>BMW</key>
<dict>
<key>name</key>
<string>BMW</string>
<key>color</key>
<string>blue</string>
<key>price</key>
<integer>40000</integer>
</dict>
我也有一个UITableView的,我从这个plist中的一些汽车填满它。
NSEnumerator *enumerator = [dictionary objectEnumerator];
id returnValue;
while ((returnValue = [enumerator nextObject]))
{
if ([[returnValue valueForKey:@"color"]isEqualToString:@"blue")
{
[array addObject:[returnValue valueForKey:@"name"]];
}
问:当我与它的一些汽车的UITableView的,我怎么能由现在的价格对它们进行排序?例如,宝马比福特便宜,所以它应该在第一个电池,而福特必须在第二个电池。我知道Apple已经创建了简单的排列数组的方法,但我怎样才能在这里使用它?谢谢 ! 最大
答
尝试this:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
答
首先提取价值成list.Then使用NSSorDescriptor。
{
NSArray *carArray=[[NSArray alloc] initwithContentsofFile:@"youFileName" ofType:@"plist"];
NSmutableArray *priceList=[[NSMutableArray alloc] init];
for(int index=0;index<[carArray count];index++)
{
NSDictionary *valueList=[carArray objectAtIndex:index];
[priceList addObject:[valueList objectForKey:@"Price"]];
}
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES];
[priceList sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
现在您将得到基于价格的排序数组。 }
谢谢!但我的应用程序崩溃: '终止应用程序,由于未捕获的异常'NSUnknownKeyException',原因:'[<__ nscfstring> valueForUndefinedKey:]:此类不是密钥值编码兼容的关键价格。'' – SmartTree
很好很容易和额外的帮助兄弟。 + 1 –