iphone - 在循环中递减日期时发生泄漏

标签 iphone objective-c memory-leaks nsdate

我在修复 Instruments 检测到的泄漏时遇到了一些麻烦。我正在尝试使用 dateByAddingComponents:toDate:options: 减少循环中的日期方法NSCalendar ,并且我不断泄漏 NSDate对象(准确地说是 49 个)。

这是我的代码:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Get current date
NSDate *date = [NSDate date];
// Create an NSDateComponents object that will be used to decrement the date
NSDateComponents *decStep = [[NSDateComponents alloc] init];
[decStep setDay:-1];

for (NSUInteger i = 49; i >= 0 ; i--)
{
    // Insert the date object in an array
    [self.fooArray insertObject:date atIndex:0];
    // Decrement the date
    date = [gregorian dateByAddingComponents:decStep toDate:date options:0];
}

// Release calendar and date components objects
[decStep release];
[gregorian release];

我尝试通过几种不同的方法来修复此泄漏,但由于我不明白它为什么会泄漏,所以我真的不知道我在做什么。您是否有任何线索可以帮助我解决此问题,因为我知道我不想使用 NSAutoreleasePool

最佳答案

你认为你为什么会泄漏?如果只是 Instruments 报告您现在多了 50 个日期对象,那么这是真的。它们将一直保留到您将 self.fooArray 设置为其他内容为止,此时(如果您使用 setter),它们将被释放。

关于iphone - 在循环中递减日期时发生泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6624841/

相关文章:

iphone - 从通讯录中获取记录时,应用程序崩溃

ios - 是否有任何通知可以捕获 iPhone 6 上的可达性事件?

ios - GoogleMaps 不是 dylib : Error at compile time with pod file

objective-c - 使用控件播放音频

objective-c - 调用 makeViewWithIdentifier :owner: causes ARC to re-create ivar

objective-c - 编辑 NSMutableArray 中的一个对象也会更改 NSMutableArray 中的另一个对象

c - *** 检测到 glibc *** outfile : free(): invalid pointer: ***

iphone - NSDictionary 与自定义对象

android - 在内存不足之前,GC 不应该在 Xamarin.Android 中自动运行吗?

gcc - 当 Address Sanitizer 说该平台不支持 detect_leaks 时,我应该解决什么问题?