我正在尝试覆盖NSURLConnection代表,但我不知道从哪里开始,有人可以提供更多种类的信息和一些示例代码吗?
我想扩展connectionDidFinishLoading委托。并继续查看我回来的JSON-String是否为用户报告了一些错误。
在我看来,扩展委托的最佳方式。甚至可能吗?
答案 0 :(得分:1)
扩展协议将允许您添加方法。但是,如果您向<NSURLConnectionDelegate>
添加更多方法,这并不意味着NSURLConnection
将使用它们:)
为什么不能将错误检查代码放在connectionDidFinishLoading
方法中,即
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Check your json here
}
答案 1 :(得分:1)
如果我已经正确理解了您要实现的目标,请执行以下操作:
NSURLConnection
并将其配置为获取JSON文件。如果我的理解是正确的,那么您不需要扩展NSURLConnectionDelegate
协议。您所需要做的就是实现NSURLConnectionDelegate。委托模式允许更改类的行为。 (在其他语言/框架中,您解释的行为将通过子类实现.URL Connection类将被子类化,并且方法和覆盖以更改行为。)在阅读Cocoa Design Patterns时可能值得您。
创建对象的类通常是其委托。以下代码显示了连接的创建以及相应的委托方法实现。
@interface SOViewController : UIViewController <NSURLConnectionDelegate> //this simply tells the compiler that SOViewController implements the NSURLConnectionDelegate protocol. If you excluded you will get a compiler warning but the code will behave correctly. You should include it.
//...
@property(readwrite, nonatomic, retain) NSURLConnection *connection;
@property(readwrite, nonatomic, retain) NSMutableData *data;
@end
@implementation SOViewController
//...
-(void)setupJSONFetch:(NSURL *)url
{
NSURLRequest *request = [NSURLRequest requestWithURL: url]; //create a request
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; //create a connection and set self as the delegate
self.connection = connection; //keep a reference to the connection
self.data = [NSMutableData data]; //create an object to store the downloaded data
[connection start]; //go!
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//store the downloaded data
[self.data appendData: data];
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
//Check self.data is as expected
}
//...
@end
值得注意的是,NSURLConnection
委托方法在iOS 5中进行了重组。
答案 2 :(得分:0)
在你的.h文件中: -
@interface YourViewController : UIViewController<YourDelegate>{
}
@end
在您的.m文件中: -
实施方法: -
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
self.responseData = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
}
我认为this link可以帮助你......:)