我不太了解委托模式中的内存管理。
在 Controller 中,如果它拥有该对象。我们应该为它分配一个强指针。这样它所拥有的对象就不会丢失。
我创建了一个小型库类来帮助我进行异步连接,它拥有一个指向采用其协议的 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
只是一个局部变量,视图控制器并没有对它持有强引用。所以在我看来,它应该在方法完成执行时被杀死。但是,它可以是活动的并将数据发送回 ViewController。
委托方法
- (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 的委托方法:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[_delegate finishConnectionWithData:_downloadData connection:self];
}
我尝试两次记录连接对象的内存地址,它们是不同的。(我按了两次按钮)。所以我想知道连接对象什么时候会被杀死。