我已经自学了一段时间的Objective C,但仍然不太明白内存管理。什么时候应该释放属性?
例如,我有一个类来处理两个不同的URLRequest连接(register和updateParticulars)。当registerConnection完成时,将执行updateParticularsConnection。
@interface ConnectionViewController : UIViewController {
}
@property (nonatomic, retain) NSURLConnection *registerConnection;
@property (nonatomic, retain) NSURLConnection *updateParticularsConnection;
@property (nonatomic, retain) NSMutableData *responseData;
@property (nonatomic, retain) NSMutableURLRequest *requestURL;
@end
@implementation ConnectionViewController
@synthesize registerConnection, updateParticularsConnection, responseData, requestURL,
(void)performRegistration {
// other here to prepare the data.
requestURL = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myURL"]];
registerConnection = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES];
}
(void)updateParticulars {
// other here to prepare the data.
[requestURL setURL:[NSURL URLWithString:@"http:myURL.com"]];
updateParticularsConnection = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES];
}
处理委托回调
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[SVProgressHUD dismissWithError:@"Unable to connect"];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (responseData == nil) {
responseData = [[NSMutableData alloc] init];
}
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection == registerConnection) {
NSMutableString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Register connection recieved data reads : %@", responseString);
if ([responseString isEqualToString:@"-1"]) { // error. stop connection
[self.requestURL release]; // remember to release requestURL since we would not be continuing on.
}
else if ([responseString isEqualToString:@""]) { // error. stop connection
[self.requestURL release]; //remember to release requestURL since we would not be continuing on.
}
else {
[self updateParticulars]; // perform next connection, updateParticulars
}
responseData = nil; // clear the current stored data in preparation for the next connection.
[self.registerConnection release];
[responseString release];
} // end of definition for register connection
else if (connection == updateParticularsConnection) {
// do stuff with data received back here
self.responseData = nil;
[self.requestURL release];
[self.updateParticularsConnection release];
}
}
我的问题是,我应该尽快释放我的属性,这也是我现在正在做的吗?还是只在dealloc方法中释放?如果我做得不对,请给予建议。