在下面的行我得到内存泄漏

时间:2012-11-29 07:58:33

标签: ios

NSDate *today = [[NSDate alloc] init];
    NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *onset = [[NSDateComponents alloc] init];
    [onset setMonth:monthsStart];
    NSDate *fromDate = [gregorian dateByAddingComponents:onset toDate:today options:0];
    [onset setMonth:monthsEnd];
    NSDate *toDate = [gregorian dateByAddingComponents:onset toDate:today options:0];

它说: -

  1. Method返回具有+1保留计数的Objective-C对象
  2. 对象泄露:分配并存储到today中的对象稍后未在此执行路径中引用,并且保留计数为+1

1 个答案:

答案 0 :(得分:0)

泄密是因为您没有发布today。请使用[today release]并发布相同内容。 calenderonset的情况也是如此。在NSDate *toDate = [gregorian dateByAddingComponents:onset toDate:today options:0];行之后,请立即释放所有这些参数。

NSDate *today = [[NSDate alloc] init];
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *onset = [[NSDateComponents alloc] init];
[onset setMonth:monthsStart];
NSDate *fromDate = [gregorian dateByAddingComponents:onset toDate:today options:0];
[onset setMonth:monthsEnd];
NSDate *toDate = [gregorian dateByAddingComponents:onset toDate:today options:0];
//After you are done with the below variables, you can release it
[today release];
[calender release];
[onset release]; //you cannot use these variables after this line.

查看此文档Advanced Memory Management Programming Guide