我对iOS开发相当新,我试图从URL中获取内容。我使用Apple教程使用NSURLConnection,一切正常,但我没有获取数据。我环顾四周,无法找到我的问题的答案。我也在我的项目中使用ARC,可能会导致问题?NSURLConnection与ARC没有收到数据
这里是我使用的,从我的头文件中的代码:
@interface ViewController : UIViewController
@property (nonatomic, retain) NSMutableData *receivedData;
@end
实现文件:
@implementation ViewController
@synthesize receivedData;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"1. viewDidLoad");
// Create the request
NSURLRequest *request = [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 *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(@"2. connection succeeded");
receivedData = [NSMutableData data];
} else {
NSLog(@"2. connection failed");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"3. didReceiveResponse");
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"4. Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"4. Succeeded! Received %d bytes of data", [receivedData length]);
}
所有的NSLog正在努力,但它口口声声说receivedData有0字节。我找不到我的问题的答案,所以我希望我能找到我的答案与这个问题。
ARC不应该用于自动引用计数,请阅读标记wiki。 – 2012-04-10 21:14:33
对不起, – 2012-04-11 11:56:25
Lars,对于ARC代码,你的'@ property'应该使用'strong'而不是'retain'。另外,为什么在'-connection:didReceiveData:'方法中没有记录语句?安德鲁 – adonoho 2012-04-11 13:30:17