我的应用使用Core Data,我在CoreData Date中添加了一个属性。 恢复值如下:
- (void)fetchedResults {
// Core Data
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [delegate managedObjectContext];
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date == %@) AND (date <= %@)", [_meetingArray valueForKey:@"when"], [_meetingArray valueForKey:@"when"]];
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"listingID != %@", [_meetingArray valueForKey:@"when"]];
NSFetchRequest *execQuery =[[NSFetchRequest alloc] init];
NSEntityDescription *descOggetto = [NSEntityDescription entityForName:@"Meetings" inManagedObjectContext:context];
[execQuery setEntity:descOggetto];
// [execQuery setPredicate:predicate];
NSError *error = nil;
_meetingArray = [context executeFetchRequest:execQuery error:&error];
_results = [context executeFetchRequest:execQuery error:&error];
NSError *saveError = nil;
[context save:&saveError];
}
使用方法 viewDidLoad ,我创建数组和词典,然后指示它们:
- (void)viewDidLoad {
[super viewDidLoad];
[self fetchedResults];
_myArr = [NSArray arrayWithObject:[_meetingArray valueForKey:@"when"]];
_myDict = [NSMutableDictionary dictionaryWithObject:_myArr forKey:@"when"];
_unsortedDays = _myDict[@"when"][0];
_sortedDays = [_unsortedDays sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"unsorted: %@, sorted: %@", _unsortedDays, _sortedDays);
NSLog(@"sorted count: %ld", _sortedDays.count);
}
并且来自此输出:
2014-03-19 18:38:32.218 GroupData[8815:70b] unsorted: (
"2014-03-19 16:00:33 +0000",
"2014-03-20 17:00:33 +0000",
"2014-03-21 14:00:33 +0000",
"2014-03-17 14:00:33 +0000",
"2014-03-18 15:00:33 +0000",
"2014-03-20 17:45:56 +0000",
"2014-03-20 17:45:56 +0000"
), sorted: (
"2014-03-17 14:00:33 +0000",
"2014-03-18 15:00:33 +0000",
"2014-03-19 16:00:33 +0000",
"2014-03-20 17:00:33 +0000",
"2014-03-20 17:45:56 +0000",
"2014-03-20 17:45:56 +0000",
"2014-03-21 14:00:33 +0000"
)
2014-03-19 18:38:32.219 GroupData[8815:70b] sorted count: 7
现在,如何删除重复的结果?
答案 0 :(得分:0)
NSSet怎么样?
NSSet aSet = [NSSet setWithArray: _unsortedDays];
现在 unsortedDays 数组中的所有字符串都是 aSet 对象。
您希望数据作为数组退出集合中吗?
_unsortedNoDupes = [aSet allObjects] ;
我希望这就是你要找的东西?
答案 1 :(得分:0)
您需要遍历日期,将日期部分存储在集合中,并删除日期(如果已使用)。
此代码会将日期的一部分转换为字符串,如果之前遇到过日期字符串,则从数组中删除该项目。
NSMutableSet *usedDays = [NSMutableSet new];
for (int i=0; i<[_sortedDays count]; i++) {
NSDate *date = _sortedDays[i];
NSString *dateString = [date descriptionWithCalendarFormat:@"%Y-%m-%d" timeZone:nil locale:nil];
if ([usedDays containsObject:dateString]) {
// This day has already been used. Remove this date from the array.
[_sortedDays removeObjectAtIndex:i];
i--;
} else {
// This is a new day, mark it as having been used
[usedDays addObject:dateString];
}
}
请注意,如果日期来自不同的区域设置/时区,您可能会遇到问题。在这种情况下,请确保它们已规范化,并且说明使用您在代码中其他位置使用的相同区域设置。