本文介绍了在Objective-C中实现代理模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个处理NSURLConnection请求的类。为了允许其他类使用这个类,我想允许主类在connectionDidFinishLoading被触发时调用一个委托。



我看过很多文档,但是我找不到任何明确例子的东西,而且由于某些原因,我没有调用代码。我现在的代码是(代码不相关):



接口:

 code> @interface PDUrlHandler:NSObject {
id delegate;
}
- (void)searchForItemNamed:(NSString *)searchQuery;
@property(nonatomic,assign)id delegate;
@end
@interface NSObject(PDUrlHandlerDelegate)
- (void)urlHandler:(PDUrlhandler *)urlHandler searchResultsFinishedLoading:(NSDictionary *)resultData;
@end

实施:

   - (void)connectionDidFinishLoading :( NSURLConnection *)连接{
NSLog(@Fininshed Loading ...);
resultData = [self parseJSON:jsonData];

if(delegate&&&[] delegate responsesToSelector:@selector(urlHandler:searchResultsFinishedLoading :)]){
NSLog(@Delegating!);
[delegate urlHandler:self searchResultsFinishedLoading:resultData];
} else {
NSLog(@不委派,我不知道为什么);
}

}

其他类中的代理:

   - (void)urlHandler:(PDUrlhandler *)urlHandler searchResultsFinishedLoading:(NSDictionary *)resultData; 
{
NSLog(@Delegating !!!!);
}


解决方案

原来我忘了设置代表:

  [currentHandler setDelegate:self]; 

需要执行初始调用PDUrlHandler的行。


I am building a class that handles NSURLConnection requests. To allow other classes to use this class, I would like to allow the main class to call a delegate when connectionDidFinishLoading is fired.

I've looked through lots of documentation, but I can't find anything that gives any clear examples, and the code that I have doesn't call the delegate for some reason. The code I have so far is (code not relevant removed):

Interface:

@interface PDUrlHandler : NSObject {
id delegate;
}
- (void)searchForItemNamed:(NSString *)searchQuery;
@property (nonatomic, assign) id delegate;
@end
@interface NSObject (PDUrlHandlerDelegate)
- (void)urlHandler:(PDUrlhandler*)urlHandler searchResultsFinishedLoading:(NSDictionary *)resultData;
@end

Implementation:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Fininshed Loading...");
    resultData = [self parseJSON:jsonData];

    if(delegate && [delegate respondsToSelector:@selector(urlHandler:searchResultsFinishedLoading:)]) {
        NSLog(@"Delegating!");
        [delegate urlHandler:self searchResultsFinishedLoading:resultData];
    } else {
        NSLog(@"Not Delegating. I dont know why.");
    }

}

The delegate within the other class:

- (void)urlHandler:(PDUrlhandler*)urlHandler searchResultsFinishedLoading:(NSDictionary *)resultData;
{
    NSLog(@"Delegating!!!!");
}
解决方案

Turns out I forgot to set the delegate:

[currentHandler setDelegate:self];

needed to go after the line that makes the initial call to the PDUrlHandler.

这篇关于在Objective-C中实现代理模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:24