更新
将此作为问题发布到 AFNetworking 存储库后,事实证明这实际上是我的使用问题。根据对我的问题的回复:
NSURLSession retains its delegate (i.e. AFURLSessionManager). Call invalidateSessionCancelingTasks: to ensure that sessions finalize and release their delegate.
所以,长话短说:如果您以下面描述的方式使用 AHTTPSessionManager
,请确保调用 invalidateSessionCancelingTasks:
以确保 session 完成并释放它们的委托(delegate)
原始问题
我有一个名为 GTAPIClient
的子类 AFHTTPSessionManager
,我用它来连接到我的 REST API。我意识到文档状态可以用作单例,但在某些情况下我需要创建一个新实例。但是,似乎每当我这样做时,该对象就永远不会被释放。目前,GTAPIClient
在释放时除了 NSLog
本身外什么都不做。
这是一些演示行为的示例代码
GTAPIClient.m
@implementation GTAPIClient
- (void)dealloc
{
NSLog(@"Dealloc: %@", self);
}
@end
GTViewController.m
#import "GTBaseEntityViewController.h"
//Models
#import "GTBaseEntity.h"
//Clients
#import "GTAPIClient.h"
@interface GTBaseEntityViewController ()
@property (nonatomic, weak) GTAPIClient *client;
@property (nonatomic, weak) GTBaseEntity *weakEntity;
@end
@implementation GTBaseEntityViewController
- (IBAction)makeClient:(id)sender {
self.client = [[GTAPIClient alloc] init];
NSLog(@"I just made an API client %@", self.client);
//Another random object assigned to a similar property, just to see what happens.
self.weakEntity = [[GTBaseEntity alloc] init];
NSLog(@"I just made a random object %@", self.weakEntity);
}
- (IBAction)checkClient:(id)sender {
NSLog(@"Client: %@", self.client);
NSLog(@"Entity: %@", self.weakEntity);
}
@end
NSLog输出
启动 makeClient:
//It seems to me that both NSLog's should return (null) as they are assigning to a weak property
2014-06-22 16:41:39.143 I just made an API client <GTAPIClient: 0x10b913680, baseURL: (null), session: <__NSCFURLSession: 0x10b915010>, operationQueue: <NSOperationQueue: 0x10b9148a0>{name = 'NSOperationQueue 0x10b9148a0'}>
2014-06-22 16:41:39.144 I just made a random object (null)
触发 checkClient
//Again, both NSLog's should return null for the two objects. However...client is still around. Also, it's overridden dealloc method never fired.
2014-06-22 16:44:43.722 Client: <GTAPIClient: 0x10b913680, baseURL: (null), session: <__NSCFURLSession: 0x10b915010>, operationQueue: <NSOperationQueue: 0x10b9148a0>{name = 'NSOperationQueue 0x10b9148a0'}>
2014-06-22 16:44:43.723 Entity: (null)
作为引用,我使用的是 AFNetworking v2.3.1。编译器警告我,将保留的对象分配给 weak 属性将在分配后释放 - 这是正确的,并且对我的随机对象具有预期的功能。应用程序中没有其他任何事情发生。没有其他 View Controller ,GTAPIClient
上没有其他方法,所有单例功能都被删除。对我在这里做错了什么有什么想法吗?
最佳答案
在此处发布 Mattt Thompson 的回复以帮助 future 的读者:
NSURLSession
retains its delegate (i.e.AFURLSessionManager
). CallinvalidateSessionCancelingTasks:
to ensure that sessions finalize and release their delegate.
如果像许多应用一样,您的应用对整个应用使用单例 session 管理器和一个 URL session ,那么您无需担心这一点。
关于objective-c - AFHTTPSessionManager 未解除分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24355635/