【问题标题】:Obj-C - NSArray missing data when looping through?Obj-C - NSArray 循环时缺少数据?
【发布时间】:2021-04-14 20:29:49
【问题描述】:

我正在尝试使用以下代码循环遍历我的数组 (finalArray):

AppDelegate.m

 NSUserDefaults *final = [NSUserDefaults standardUserDefaults];
         NSArray *finalArray = [final objectForKey:@"notifyTimes"];

      NSLog(@"Time from AppDelegate in Background %@", finalArray);
    
    for (int i = 0; i<finalArray.count; i++) {
        
        NSString *dateString = [finalArray objectAtIndex:i++];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM d yyyy h:mm a"];
    NSDate *dateFromString = [dateFormatter dateFromString:dateString];
    
    NSLog(@"Date according to app delegate frm string %@", dateFromString);

        UILocalNotification *notification = [[UILocalNotification alloc]init];
        notification.fireDate =  dateFromString;

        [notification setAlertBody:@"Reminder: You have an upcoming appointment!"];
   
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }

由于某种奇怪的原因,当我第一次记录 finalArray 时(在我的循环之外),返回了以下数据,这是正确的:

Time from AppDelegate in Background (
    "Apr 14 2021 12:04 PM",
    "Apr 17 2021 12:27 PM",
    "Apr 27 2021 12:28 PM",
    "Apr 14 2021 12:47 PM",
    "Apr 30 2021 1:45 PM",
    "Apr 27 2021 1:45 PM",
    "Apr 14 2021 12:03 PM",
    "Apr 30 2021 11:46 AM",
    "Apr 29 2021 11:20 AM",
    "Apr 14 2021 12:40 PM",
    "Apr 14 2021 12:56 PM",
    "Apr 14 2021 1:20 PM",
    "Apr 14 2021 1:08 PM",
    "Apr 14 2021 1:20 PM"
)

但是当我遍历同一个数组并记录结果时,循环会丢失上面记录的多个日期:

2021-04-14 13:21:04.485190-0700 [18644:1261621] Date according to app delegate frm string Wed Apr 14 12:04:00 2021
2021-04-14 13:21:04.493588-0700 [18644:1261621] Date according to app delegate frm string Tue Apr 27 12:28:00 2021
2021-04-14 13:21:04.494519-0700 [18644:1261621] Date according to app delegate frm string Fri Apr 30 13:45:00 2021
2021-04-14 13:21:04.495384-0700 [18644:1261621] Date according to app delegate frm string Wed Apr 14 12:03:00 2021
2021-04-14 13:21:04.496157-0700 [18644:1261621] Date according to app delegate frm string Thu Apr 29 11:20:00 2021
2021-04-14 13:21:04.496913-0700 [18644:1261621] Date according to app delegate frm string Wed Apr 14 12:56:00 2021
2021-04-14 13:21:04.497700-0700 [18644:1261621] Date according to app delegate frm string Wed Apr 14 13:08:00 2021

对为什么会发生这种情况有任何见解吗?

【问题讨论】:

    标签: ios arrays objective-c


    【解决方案1】:

    你正在增加i inside你在这一行的循环:

    NSString *dateString = [finalArray objectAtIndex:i++];
    

    你可能只是想要:

    NSString *dateString = [finalArray objectAtIndex:i];
    

    通过在循环内递增,您无意中跳过了所有其他元素。

    【讨论】:

    • 啊,完全监督。谢谢你。哈哈,这让我精神崩溃。
    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 2013-10-07
    • 1970-01-01
    • 2019-12-28
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    相关资源
    最近更新 更多