【问题标题】:In the below line i get memory leak在下面的行中我得到内存泄漏
【发布时间】:2012-11-29 07:58:33
【问题描述】:
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. 方法返回一个具有 +1 保留计数的 Objective-C 对象
  2. 对象泄露:分配并存储到today 的对象在此执行路径的后面没有被引用,并且保留计数为+1

【问题讨论】:

标签: ios


【解决方案1】:

泄漏是因为你没有释放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

【讨论】:

  • 很好的双关语:今天不发布。大声笑。
  • 是的,现在才注意到。 :)
  • @BhartiSyal,在这种情况下,请使用我们在上一个问题中讨论的 release/autorelease。对代码中适当位置的所有 alloc/retain 语句执行此操作。
  • [首发];发作=无;我应该在释放它之后将它设置为 nil
  • 你可以这样做。只是为了确保在释放后没有垃圾值。我更喜欢通常将其设置为 nil。
猜你喜欢
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
相关资源
最近更新 更多