委托并在NSURLConnection中声明变量receivedData

时间:2013-01-31 21:42:13

标签: ios objective-c nsurlconnection

我想在Xcode 4.5.2 for iOS中创建一个NSURLConnection委托,因为documentation 建议它。现在我将以下代码(直接从文档中提取)放入方法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

1 个答案:

答案 0 :(得分:1)

你不应该在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);
}