2015-03-31 61 views
0

我有一個問題,我有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中插入的日期相匹配的通知?

回答

0

的問題是,這個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]; 
    } 
} 
+0

非常感謝你,我測試一切正常。非常感謝!!!!! – 2015-03-31 12:08:56