1

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中断 for 循环(我将对象添加到数组中)。但是我找不到问题,我在谷歌上搜索过同样的问题,但仍然没有运气。

谁能帮助我做错了什么?

4

1 回答 1

2

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

而不是dateByAddingTimeInterval:使用NSCalendardateByAddingComponents:toDate:options:

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)

于 2013-08-09T09:50:13.047 回答