記憶體流失問題的解決
記憶體流失(Memory Leaks)是當一個對象或變數在使用完成後沒有釋放掉,這個對象一直佔有著這塊記憶體,直到應用停止。如果這種對象過多記憶體就會耗盡,其它的應用就無法運行。這個問題在C++、C和Objective-C的MRR中是比較普遍的問題。
在Objective-C中釋放對象的記憶體是發送release和autorelease訊息,它們都是可以將引用計數減1,當為引用計數為0時候,release訊息會使對象立刻釋放,autorelease訊息會使對象放入記憶體釋放池中延遲釋放。
上代碼:
- (void)viewDidLoad { [super viewDidLoad]; NSBundle *bundle = [NSBundle mainBundle]; NSString *plistPath = [bundle pathForResource:@"team" ofType:@"plist"]; //擷取屬性列表檔案中的全部資料 self.listTeams = [[NSArray alloc] initWithContentsOfFile:plistPath]; } - (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]; } 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; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger row = [indexPath row]; NSDictionary *rowDict = [self.listTeams objectAtIndex:row]; NSString *rowValue = [rowDict objectForKey:@"name"]; NSString *message = [[NSString alloc] initWithFormat:@”您選擇了%@隊。”, rowValue]; UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@”請選擇球隊” message:message delegate:self cancelButtonTitle:@”Ok” otherButtonTitles:nil]; [alert show]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; }