【问题标题】:Why object is leaked (Objective C)为什么对象被泄露(目标 C)
【发布时间】:2014-06-05 21:26:40
【问题描述】:

有人能解释一下为什么对象引用末尾有计数器 1 吗?

5   Malloc  +1  1   00:03.412.584   Control -[PaymillPaymentService createServiceRequestWith:and:]
6   Autorelease         00:03.412.596   Control -[PaymillPaymentService createServiceRequestWith:and:]
7   Retain  +1  2   00:03.412.608   libsystem_sim_blocks.dylib  _Block_object_assign
8   Retain  +1  3   00:03.412.620   Control -[DashboardViewController requestMainTransactionsList]
9   Release -1  2   00:03.506.116   UIKit   _UIApplicationHandleEvent
10  Release -1  1   00:04.104.252   Control -[DashboardViewController transactionListLoadingComplete:]

5,6) 调用alloc/init(工厂方法),将autorelease对象返回给调用者

- (ServiceRequest*)createServiceRequestWith:(NSString*)url and:(id)delegate
{
    NSURL *fullURL = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:fullURL] autorelease];
    [NSMutableURLRequest basicAuthForRequest:request  withUsername:[self accessToken] andPassword:@""];

    ServiceRequest *serviceRequest = [[ServiceRequest alloc]  initWithURLRequest:request forDelegate:delegate];

    return [serviceRequest autorelease];
} 

7) 作为参数传递给块

__unsafe_unretained id blockRequest = serviceRequest;
[operation setCompletionBlock:^{
    [self handleTransactionListRequest:blockRequest];

}];

8) 保持分配给强属性

ServiceRequest* request = [[[AppController sharedController] currentService] retrieveTransactionListInto:transactionList usingInterval:timeInterval forDelegate:self];
request.tag = @"main";
self.currentMainRequest = request;

9) ??? (可能会阻止释放)

10) 财产释放

 [currentMainRequest release];

据我了解,第一个 malloc 保持不平衡,但第一个 malloc 创建对象,它总是 +1 !!!

【问题讨论】:

    标签: objective-c memory-leaks


    【解决方案1】:

    块保留它们引用的对象。

    7   Retain  +1  2   00:03.412.608   libsystem_sim_blocks.dylib  _Block_object_assign
    

    尝试在变量旁边使用__block 关键字,以防止它被块保留。

    【讨论】:

    • 这是一个很好的评论。添加了 __block 但目前我的对象基本上立即被释放,尽管有其他保留...进一步调查...
    • 另外我实际上需要块中的这个对象,可以吗?
    • 你是对的,在我以其他方法移动自动释放后,对象被正确释放。所以基本上在我的原文中,7)块保留是不平衡的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 2012-05-04
    • 2012-06-06
    • 2014-02-25
    • 2011-06-11
    • 2012-01-19
    相关资源
    最近更新 更多