The release object in MRR is implemented through the release or autorelease message. The release message immediately releases the reference count-1. Sending the autorelease message will put the object into the memory release pool for delayed release, the reference count of the object does not change. Instead, it adds a record to the memory release pool until all objects in the pool are notified to send the release message to reduce the reference count.
Because it will delay object release, unless required, do not use autorelease to release objects. In iOS programs, the default memory release pool is released after the program ends, and the application entry is main. the M file code is as follows:
int main(int argc, char *argv[]){@autoreleasepool {return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));}}
The code is wrapped in @ autoreleasepool {... }. This is the scope of the pool. By default, it is the entire application. If you use autorelease to release a large number of objects, memory leakage may occur. So when is autorelease required? Let's look at the following code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{static NSString *CellIdentifier = @”CellIdentifier”;UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];if (cell == nil) {cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];}NSUInteger row = [indexPath row];NSDictionary *rowDict = [self.listTeams objectAtIndex:row];cell.textLabel.text = [rowDict objectForKey:@"name"];NSString *imagePath = [rowDict objectForKey:@"image"];imagePath = [imagePath stringByAppendingString:@".png"];cell.imageView.image = [UIImage imageNamed:imagePath];cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;return cell;}
The cell object cannot be release immediately. We need to use it to set the table view screen. Autorelease is generally used in methods that provide objects for other callers. Objects cannot be release immediately in this method, but need to be released in a delayed manner.
In addition, autorelease is also used, that is, the "Class-level Constructor" mentioned above ":
Nsstring * message = [nsstring stringwithformat: @ "you have selected the % @ Team. ", Rowvalue];
Although the ownership of this object is not the current caller, it is put into the pool by the IOS system by sending the autorelease message. Of course, this is invisible to developers, we should also pay attention to reducing the use of such statements.