我正在为一个对象创建自己的委托,但我发现了一些问题......当我的委托被调用时,对象 Client 不存在于内存中。
如果我将 Client Object 声明为 UIViewController 的属性,问题就解决了,但我认为这不是一个好的解决方案。
为什么我的对象不在内存中?
更新示例代码:
//Class UIViewController
-(void)viewDidLoad {
[super viewDidLoad];
Client *client = [[Client alloc] initWithDelegate:self];
[client login]; //It has two delegates methods (start and finish)
}
//In the same class, the delegate methods:
- (void) start
{
//DO START STUFF
}
-(void) finish
{
// DO FINISH STUFF
}
客户端.h
@interface Client : NSObject <IClient>
@property (nonatomic,assign) id<IClient> _delegate;
-(void)login;
-(id)initWithDelegate:(id<IClient>)delegate;
@end
客户端.m
@implementation Client
@synthesize _delegate;
//Constructor
- (id) initWithDelegate:(id)delegate
{
self = [super init];
if(self)
{
self._delegate = delegate;
}
return self;
}
-(void)login
{
//Do stuff asynchronously like NSURLConnection
//Not all code, just a part:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:NO];
[connection start];
}
//Delegate method of NSURLConnection that login method fires
//Just implemented one method delegate of NSURLCOnnection for the example
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
NSLog(@"ERROR");
[_delegate stop]; //<---CRASH!!!
}
@end
客户端.h
@protocol IClient <NSObject>
- (void) start;
- (void) finish;
@end
当我使用NSURLConnection
时,委托方法像 param the own 一样传递NSURLConnection
,但我不知道我需要如何实现我的委托,如下所示:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response