我陷入了这个问题,我有一个UITableView,并用NSMutableArray中的数据填充它。数组具有以下结构:
<array>
<dict>
<key>Date</key>
<string>2011.18.09 04:17 PM</string>
<key>Value</key>
<string>58.00</string>
</dict>
<dict>
<string>2011.15.09 04:21 PM</string>
<key>Value</key>
<string>0.00</string>
</dict>
</array>
我想在数组中的每一天都有一部分。我已经弄清楚了如何返回日期数,并为节标题命名,我唯一的问题是返回每个节的行数,然后为每行定义单元格。
工作代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"savedData.daf"];
NSMutableArray *d = [NSMutableArray arrayWithContentsOfFile:path];
NSMutableArray *test = [d valueForKey:@"Date"];
NSString *g = [[NSString alloc] init];
NSString *s = [[NSString alloc] init];
c = 0;
for (g in test) {
s = [g substringToIndex:[g length]-9];
if (![s isEqualToString:sf]) {
c = c+1;
[dates addObject:s];
}
sf = [g substringToIndex:[g length]-9];
}
return c;
该代码将计算不同的日期,并创建一个包含节名称的数组。任何人都可以帮助我定义行数(通过计算每天的对象数)以及在“cellForRowAtIndexPath”方法中为行赋予正确的值。
最佳答案
不要在上面的代码中alloc
以及init
g和s,这不是必需的,并且会导致内存泄漏。
我将遍历您的数组并创建另一个包含字典的数组。每个字典将包含两个对象,一个日期和一个数组。该数组将保存适用于每个日期的所有值。
使用此技术,主数组的计数将是段的数量,每节的行将是字典中保存的数组的计数。每行的值将是该节(主数组)和行(内部数组)的适当索引处的对象。
这是一些经过稍微测试的代码,它们可以满足您的要求:
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:@"test.plist"];
[array sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Date" ascending:YES]]];
NSMutableArray *datesList = [[NSMutableArray alloc] init ];
NSString *previousDate = @"";
NSMutableArray *currentDateValues;
for (NSDictionary * dict in array)
{
if ([[[dict objectForKey:@"Date"] substringToIndex:10] isEqualToString:previousDate])
{
// This is another entry from the same date
[currentDateValues addObject:[dict objectForKey:@"Value"]];
}
else
{
// We haven't seen this date before
previousDate = [[dict objectForKey:@"Date"] substringToIndex:10];
currentDateValues = [NSMutableArray array];
[currentDateValues addObject:[dict objectForKey:@"Value"]];
NSDictionary *newDate = [NSDictionary dictionaryWithObjectsAndKeys:previousDate,@"Date",currentDateValues,@"Values", nil];
[datesList addObject:newDate];
}
}
这应该为您提供一个数组
datesList
,该数组包含每个日期的字典和每个日期的所有值的数组。
关于objective-c - UITableView每天从NSMutableArray制作1个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7476628/