错误:无法在 iOS 中分配区域



每当通过调用此方法-选择UIPickerView的一行时,我都会将对象添加到可变数组中

-(void)setScheduleStartDate:(NSString *)dateStr
{
    [scheduleDatesArray removeAllObjects];
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"d MMMM yyyy";
    scheduleStartDate = [df dateFromString:dateStr];
    /******* getting array of schedule dates     ***********/
    NSDate* scheduleEndDate = [scheduleStartDate dateByAddingTimeInterval:60*60*24*28*6]; // add six month (of 28 days) in schedule start date
    double endMS = [scheduleEndDate timeIntervalSinceDate:scheduleStartDate];
    for (double i =0; i < endMS; i = (i + 60*60*24*14)) {
        [scheduleDatesArray addObject:[NSNumber numberWithDouble:i]];
    }
}

在多次调用此方法后,我崩溃了,出现了此错误消息

malloc: *** mmap(size=627101696) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug

通过在malloc_error_break中设置断点,我的应用程序进入循环(在循环中我将对象添加到数组)。但我找不到问题,我在谷歌上搜索过同样的问题,但仍然没有找到。

有人能帮我做错事吗?

你真的不应该基于一个月是28天,甚至一分钟是60秒的假设来计算日期。

使用NSCalendardateByAddingComponents:toDate:options: 代替dateByAddingTimeInterval:

NSDateComponents *sixMonthComponents = [[NSDateComponents alloc] init];
sixMonthComponents.month = 6;
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate* scheduleEndDate = [currentCalendar dateByAddingComponents:sixMonthComponents toDate:scheduleStartDate options:0];

编辑:据我所知,您希望每14天向数组添加一个时间间隔(半个月,您将一个月定义为28天)。为了更健壮,我会做这样的事情(没有测试,但应该可以工作,让我知道):

// We increment i with the total interval between the two dates (endMS) divided by 12 (6 months * 2 times per month)
for (double i = 0; i < endMS; i += (endMS / 12) {
    [scheduleDatesArray addObject:@(i)];
}

旁注[NSNumber numberWithDouble:i]可以写成@(i)

最新更新