委托(delegate)模式中的内存管理我不是很懂。
在 Controller 中,如果它拥有那个对象。我们应该为它分配一个强指针。 这样它拥有的对象就不会丢失。
我创建了一个小的库类来帮助我进行异步连接,它包含一个指向采用其协议(protocol)的 ViewController 的弱指针。连接完成后,数据将发送回 ViewController。
#import <Foundation/Foundation.h>
@protocol AsyncConnectionDelegate;
@interface AsyncConnection : NSObject <NSURLConnectionDataDelegate>
@property (weak, nonatomic) id <AsyncConnectionDelegate> delegate;
-(void)callAsyncConnectionAtUrl:(NSString *)url dictionary:(NSDictionary *)dictionary method:(NSString *)method delegate:(id)delegate;
@end
@protocol AsyncConnectionDelegate <NSObject>
- (void)finishConnectionWithData:(NSData *)data connection:(AsyncConnection *)connection;
@end
用法:(按下按钮时)
// user input
NSString *username = _usernameTextField.text;
NSString *password = _pwdTextField.text;
//create dictionary key-value pair for transformming into NSData
NSMutableDictionary *loginKeyValue = [[NSMutableDictionary alloc]init];
[loginKeyValue setObject:username forKey:@"username"];
[loginKeyValue setObject:password forKey:@"password"];
AsyncConnection *conc = [[AsyncConnection alloc]init];
[conc callAsyncConnectionAtUrl:@"http://localhost:3000/login.json" dictionary:loginKeyValue method:@"POST" delegate:self];
这里的*conc
只是一个局部变量,view controller没有持有对它的强引用。所以在我看来,它应该在方法执行完毕时被杀死。但是,它可以处于事件状态并将数据发送回 ViewController。
委托(delegate)方法
- (void)finishConnectionWithData:(NSData *)data connection:(AsyncConnection *)connection{
NSLog(@"Connection Object : %@", connection );
Member *member = [Member initWithData:data];
NSLog(@"member username \n %@",member.username);
NSLog(@"member password \n %@",member.password);
NSString *msg = (member.username)?@"Login Success":@"Failed to login";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"NOTICE!!" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
该类仅使用此方法发送回数据: 就是NSURLConnection的委托(delegate)方法:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[_delegate finishConnectionWithData:_downloadData connection:self];
}
我尝试将连接对象的内存地址记录了两次,它们是不同的。 (我踢了两次按钮)。所以我想知道连接对象什么时候会被杀死。
最佳答案
行为取决于 -[AsyncConnection callAsyncConnectionAtUrl:dictionary:method:delegate:]
的实现。
如果它什么也没做,那么你是对的,你会期望 AsyncConnection *conc
在按下按钮的方法结束时被释放,因为没有其他人会保留它。
但是,-callAsyncConnectionAtUrl:
可能会导致 self
保留一段时间。 (它是否将 self
传递给可能保留它的其他代码?或者它是否包含引用 self
的 block ,然后将该 block 传递给其他代码?)
如果您想知道 AsyncConnection
在实践中何时被释放,很容易找到:将 dealloc
的实现添加到 AsyncConnection
,在其中设置一个断点,然后运行您的代码。
关于objective-c - 当局部变量持有委托(delegate)引用时,它什么时候会被杀死?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14088998/