3 iphone algorithm cocoa cocoa-touch objective-c
就解释而言,这个有点乏味,所以这里就是这样.我基本上在iPhone上填充了一个包含多个部分的tableView,每个部分可能有多行.根据我的理解,最好有一个数组数组,这样你就可以通过向顶级数组计数发送消息来简单地确定一个数组,然后是每个部分的行,对内部数组执行相同的操作(s) ).我的数据是字典的形式.字典中的一个键/值对决定了它在tableView上的显示位置.一个例子如下:
{
name: "bob",
location: 3
}
{
name: "jane",
location: 50
}
{
name: "chris",
location: 3
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我有一个包含两个子阵列的数组.第一个子阵列将包含两个包含bob和chris的词典,因为它们都是位置3的一部分.第二个子阵列将包含jane,因为她位于位置50.我在Cocoa中最好的选择是填充这个数据结构吗?C中的哈希表可能会起作用,但我宁愿使用Cocoa中可用的类.
谢谢,如果我需要进一步澄清,请告诉我.
以下代码有效:( 编辑:添加了我的初始化代码)
NSArray * arrayOfRecords = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"bob", @"name",
[NSNumber numberWithInt:3], @"location", nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"jane", @"name",
[NSNumber numberWithInt:50], @"location", nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"chris", @"name",
[NSNumber numberWithInt:3], @"location", nil],
nil];
NSMutableDictionary * sections = [NSMutableDictionary dictionary];
for (NSDictionary * record in arrayOfRecords)
{
id key = [record valueForKey:@"location"];
NSMutableArray * rows = [sections objectForKey:key];
if (rows == nil)
{
[sections setObject:[NSMutableArray arrayWithObject:record] forKey:key];
}
else
{
[rows addObject:record];
}
}
NSArray * sortedKeys = [[sections allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray * sortedSections = [sections objectsForKeys:sortedKeys notFoundMarker:@""];
NSLog(@"%@", sortedSections);Run Code Online (Sandbox Code Playgroud)