我有一个plist,它包含一个代表某个事件的NSDictionary数组,每个字典都包含一些关于该事件的信息,以及一个带有事件日期的NSDate,例如
我希望用这个日期创建一个分段的表格视图,就像日历应用程序中的日历应用程序一样,当你点击“列表”视图时,它会随iPhone一起提供。您可以看到只有日期的部分,其中有事件。
那么,从有多少个NSDictionary具有相同的日期开始,最好的方法是什么呢(这样我就知道要创建多少个部分,每个部分有多少行,因为每个部分有不同的数量或行数)。
谢谢
发布于 2010-03-28 03:51:58
我在“重新连接”上做了非常类似的事情,除了我的部分是多年的(参见历史截图)。
在步骤5结束时,您应该有一个区段数组。在该部分中,您可以向该部分发送一条消息,说明已添加到该部分的NSDictionary的数量,该部分将表示表中的每一行。
发布于 2010-03-28 06:52:58
经过一段时间的尝试,这就是我想出来的,目前它只是一个保持清晰的基础工具。
#import <Foundation/Foundation.h>
NSDate* normalizedDateWithDate(NSDate *date) {
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comp = [calendar components:unitFlags fromDate:date];
return [calendar dateFromComponents:comp];
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *plistPath = @"flights.plist";
NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];
NSMutableSet *flightDates = [[NSMutableSet alloc] init];
for (NSDictionary *oneFlight in array)
[flightDates addObject:normalizedDateWithDate([oneFlight objectForKey:@"flightDate"])];
NSLog(@"Number of Sections Required: %d", [flightDates count]);
NSMutableDictionary *datesAndFlights = [[NSMutableDictionary alloc] init];
for (NSDate *fDate in flightDates) {
NSMutableArray *sectionFlights = [[NSMutableArray alloc] init];
for (NSDictionary *oneFlight in array) {
if ([normalizedDateWithDate([oneFlight objectForKey:@"flightDate"]) isEqualToDate: normalizedDateWithDate(fDate)])
{
[sectionFlights addObject:oneFlight];
}
}
[datesAndFlights setObject:sectionFlights forKey:normalizedDateWithDate(fDate)];
[sectionFlights release];
}
NSEnumerator *enumerator = [datesAndFlights keyEnumerator];
NSDate *key;
while ((key = [enumerator nextObject])) {
NSLog(@"Key: %@", key);
for (NSDictionary *oneFlight in [datesAndFlights objectForKey:key]) {
NSLog(@"flightNumber: %@ and Total Time: %@", [oneFlight objectForKey:@"flightNumber"], [oneFlight objectForKey:@"totalTime"]);
}
}
[array release];
[flightDates release];
[datesAndFlights release];
[pool drain];
return 0;
}这只是我设法把它放在一起,它似乎是有效的,但如果谁能看到一个更好的或更简洁的方法,请说!还有在顶部的函数,我用它来确保日期总是在时间00:00:00,当我比较它的时候,我已经在文档中看到了NSCalendar - rangeOfUnit:startDate:interval:forDate:方法,有人知道使用这个方法会更好吗?
谢谢
https://stackoverflow.com/questions/2530291
复制相似问题