【问题标题】:Memory leak iOS pre 5.0.iOS pre 5.0 内存泄漏。
【发布时间】:2014-04-06 05:35:06
【问题描述】:

我正在努力找出这段代码有什么问题。我想我不太了解引用计数。在 iOS 版本中,我一直依赖 ARC。但我应该快速升级到用 4.0 到 7.0 编写的代码。运行分析显示以下错误:

方法返回一个具有 +0 保留计数的 Objective-C 对象 & 引用计数增加。

该对象现在在:[self changeSelectionTo:[[gregorian dateFromComponents:currentComps] retain]]; 行具有 +1 保留计数

对象泄露:分配的对象在此执行路径的后面没有被引用,并且在[currentPageView selectDate:selected]; 的保留计数为+1

我是 IOS 的新手,我似乎无法识别此代码中的问题。非常感谢您的帮助。

@property (nonatomic, retain) id<CalendarViewDelegate> delegate;
@property (nonatomic, readonly) NSDate *selected;

- (id)initWithDelegate:(id<CalendarViewDelegate>)d {
if (self = [super initWithFrame:CGRectMake(0, 0, 320, 480)]) {
    delegate = [d retain];

    self.backgroundColor = [UIColor whiteColor];

    gregorian = [[NSCalendar alloc]
                 initWithCalendarIdentifier:NSGregorianCalendar];

    [self createUIControls];

    NSDateComponents *currentComps =
    [gregorian components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];

    currentDay = currentComps.day;
    currentMonth = currentComps.month;
    currentYear = currentComps.year;

    showingMonth = currentComps.month;
    showingYear = currentComps.year;

    [self updateLastAndNextMonthAttributes];

    [self updateMonthHeader];

    currentPageView = [[CalendarPageView alloc] initWithMonth:showingMonth
                                                      andYear:showingYear delegate:self];
    currentPageView.frame = CGRectMake(0, 0, currentPageView.bounds.size.width, currentPageView.bounds.size.height);
    currentPageView.delegate = self;
    [pagesView addSubview:currentPageView];

// the memory leak issue seems to be in this area
    [self changeSelectionTo:[[gregorian dateFromComponents:currentComps] retain]];

    [currentPageView selectDate:selected];
    highlighted = nil;

【问题讨论】:

  • 粘贴运行时崩溃信息,您可能会因为分析器建议之外的原因而崩溃。我猜您的代码正在创建保留周期,因为我可以看到您保留了传入的委托。

标签: ios objective-c memory-leaks addsubview


【解决方案1】:

如果它说:

方法返回一个带有+0 retain countReference count incremented 的Objective-C 对象。

该对象现在在以下行具有 +1 保留计数:

[self changeSelectionTo:[[gregorian dateFromComponents:currentComps] retain]];

然后不保留它。 在将对象传递到某个地方之前保留对象也是不好的做法。处理程序应自行决定是否需要自己的对象。

我认为你需要阅读这篇关于memory management 的文章。

【讨论】:

  • 你会如何重写错误的行?谢谢
  • @user3170275, [self changeSelectionTo:[gregorian dateFromComponents:currentComps]];
  • 如果我删除了retain关键字,点击几下后代码实际上会崩溃。
猜你喜欢
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 2016-10-16
  • 2014-06-06
  • 2011-04-29
  • 1970-01-01
相关资源
最近更新 更多