For循环从核心数据
问题描述:
我有一个问题,我有2个数组(日期和descriere),一个是保持日期,我从datePicker中选择另一个是一个字符串数组,两个数组都从CoreData中获取。For循环从核心数据
-(void)generateLocalNotification {
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"AddEntrySettings"];
fetchRequest.resultType = NSDictionaryResultType;
NSArray *result = [coreDataStack.managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSMutableArray *date = [result valueForKey:@"date"];
NSMutableArray *descriere = [result valueForKey:@"descriere"];`
if (date != nil) {
for (NSString *stringDate in date) {
NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setDateFormat:@"MM/dd/yyyy h:mm a"];
[format setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
self.date = [format dateFromString:stringDate];
NSLog(@"LOG:%@",date);
localNotification.fireDate = [self.date dateByAddingTimeInterval:0];
localNotification.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
for (int i = 0; i < descriere.count; i++) {
localNotification.alertBody = descriere[i];
}
localNotification.applicationIconBadgeNumber = 1;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.userInfo = @{@"id" : @42};
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:localNotification];
}
}
}
当我尝试fireDate一切正常,每次当从阵列中的日期与本地时间匹配的时候,我收到通知,直到我尝试添加alertBody,当我做一个for循环每次alertBody显示我的NSArray的最后一个条目。在CoreData中,我在同一时间添加的两个条目。我的错误在哪里?我怎样才能让每一次都收到alertBody与我在CoreData中插入的日期相匹配的通知?
答
的问题是,这个for循环:
for (int i = 0; i < descriere.count; i++) {
localNotification.alertBody = descriere[i];
}
会,为每一位stringDate
,迭代在你descriere阵列中的最后一项。你想要的是在date
中找到stringDate
的索引,然后在descriere
中找到相同索引处的字符串。
但有一个更简单的方法。不要解压result
成两个独立的阵列,从内刚刚访问不同的值循环:
if (result != nil) {
for (NSDictionary *dict in result) {
NSString *stringDate = [dict objectForKey:@"date"];
// if necessary, test whether stringDate is nil here
NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setDateFormat:@"MM/dd/yyyy h:mm a"];
[format setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
self.date = [format dateFromString:stringDate];
NSLog(@"LOG:%@",date);
localNotification.fireDate = [self.date dateByAddingTimeInterval:0];
localNotification.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
localNotification.alertBody = [dict objectForKey:@"descriere"];
localNotification.applicationIconBadgeNumber = 1;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.userInfo = @{@"id" : @42};
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:localNotification];
}
}
非常感谢你,我测试一切正常。非常感谢!!!!! – 2015-03-31 12:08:56