2011-09-20 56 views

回答

12

啓動使用

self.responseData = [NSMutableData data]; 
NSURL *url = [NSURL URLWithString:@"http://sampleurl/"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
[connection autorelease]; 

連接,您可以看看在connectionDidFinishLoading委託方法

#pragma mark - NSURLConnection Delegate Methods 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    [self.responseData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [self.responseData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    NSLog(@"Connection failed: %@", [error description]); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
     //Getting your response string 
    NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]; 
self.responseData = nil; 
    } 

響應爲了您的內存泄漏問題

聲明在接口文件

響應數據
NSMutableData *_responseData; 

財產如下

@property (nonatomic, retain) NSMutableData *responseData; 

和合成它

@synthesize responseData = _responseData; 

不要釋放它的任何地方(我們使用便捷的構造函數分配)。我們已經在connectionDidFinishLoading方法中將它設置爲nil。

+0

如何釋放responsedata –

+0

它設置爲nil在connectionDidFinishLoading(self.responseData =零),並釋放在dealloc方法的實例變量。 ([responseData release];) – sElanthiraiyan

+0

我在self.responseData = [NSMutableData data]中得到了100%的內存泄漏問題; –

4

在iOS 5中和OS X 10.7或更高版本,可以異步使用加載數據如下:

NSURL *url = [NSURL URLWithString:@"http://sampleurl/"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] 
     completionHandler: ^(NSURLResponse * response, NSData * data, NSError * error) { 
      NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)response; 
      if(httpResponse.statusCode == 200) { 
       //your code to handle the data 
      } 
     } 
]; 

或者,如果你想同步做到這一點(不推薦,如果要加載大量的數據,因爲它會掛應用程序)(在OS X 10.2+和iOS 2.0+提供)

NSURL *url = [NSURL URLWithString:@"http://sampleurl/"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
NSURLResponse * response; 
NSError * error; 
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
+0

一個很好的簡單的答案,做了我想要的一切。謝謝! – SilentLupin

相關問題