在 NSURL 文档中委托和声明变量接收数据



我想在 iOS 版 Xcode 4.5.2 中创建一个 NSURLConnection 委托,因为文档建议这样做。现在,我将以下代码(直接取自文档)放入方法application didFinishLaunchingWithOptions:中的AppDelegate.m中。

// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere.
    receivedData = [[NSMutableData data] retain];
} else {
    // Inform the user that the connection failed.
}

如何在 AppDelegate.h 中创建委托?在哪里以及如何声明变量receivedData

您不应该在 AppDelegate 中执行此操作,而只是为了让它正常工作,您需要执行以下操作。

1) 在 AppDelegate.h 中,将接口声明替换为以下内容 ::

@interface AppDelegate : UIResponder <UIApplicationDelegate, NSURLConnectionDataDelegate> {
    NSMutableData *receivedData;
}  

2) 在您的 AppDelegate.m 中,添加此方法::

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData setData:data];
    NSLog(@"receivedData : %@", receivedData);
}

最新更新