我有一个应用程序,我需要支持,直到最初的开发人员回来。
基本上它有一种方法可以将数据分组为UITableView
的部分。
一切都很好,并按DogLocation
显示章节。
这是我的代码:
-(void)loadSortedData:(NSString*)breedToLoad fieldToSort:(NSString*)sortField
{
self.items = [DbUtilities getDogsByBreed:breedToLoad SortField:sortField];
NSMutableDictionary * theDictionary = [NSMutableDictionary dictionary];
for ( Dog * object in self.items )
{
NSMutableArray * theMutableArray = [theDictionary objectForKey:object.DogLocation];
if ( theMutableArray == nil )
{
theMutableArray = [NSMutableArray array];
[theDictionary setObject:theMutableArray forKey:object.DogLocation];
}
[theMutableArray addObject:object];
}
self.sortedMediaItems = [[theDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
/* Save `theDictionary` in an instance variable */
self.theSource = theDictionary;
[self.tableView reloadData];
}
我使用以下语法在ViewDidLoad
中调用此方法:
[self loadSortedData:@"Cattle" fieldToSort:@"DogLocation"];
我想要实现的是能够通过在方法中传递一个值来调用此方法,例如,我可以通过其他字段对其进行排序,而不仅仅是DogLocation,例如DogAge,DogPrice。
有人可以指导我或者告诉我一个更好的方法来实现这一目标,而不是写一个大的if else声明吗?
提前谢谢。
答案 0 :(得分:2)
您可以尝试使用M13OrderedDictionary,它基于NSObject而不是NSDictionary,但它完成了所需的工作:https://github.com/Marxon13/M13OrderedDictionary
答案 1 :(得分:1)
只要sortField
始终是Dog
的有效属性,您就可以使用Key-Value Coding。
for ( Dog * object in self.items )
{
id key = [object valueForKey:sortField];
NSMutableArray * theMutableArray = [theDictionary objectForKey:key];
if ( theMutableArray == nil )
{
theMutableArray = [NSMutableArray array];
[theDictionary setObject:theMutableArray forKey:key];
}
[theMutableArray addObject:object];
}