這是我在第一篇文章stackoverflow.com所以請善待(倒帶);)的Objective-C/iOS版:消息發送到釋放實例
我有,其目的是爲了顯示博客文章(導航基礎的應用標題)在表視圖(與JSON)。 我碰到的問題發生在一個單元離開屏幕然後回來時。 我得到了一個EXC_BAD_ACCESS(因爲我發送了一個消息給一個釋放的實例),所以我努力去理解它從哪裏來,我終於找到了解決方案。但事實是,我並不完全明白問題是如何發生的。這就是爲什麼我需要有人給我啓發,我認爲這是基本的理解!
當連接到JSON Web服務完成加載時,我解析JSON代碼以獲取博客文章列表(recentPosts),然後爲每篇文章(blogArticle)創建一個BlogArticle對象,將其存儲在MutableArray伊娃(allEntries),並插入到表視圖中的一行:
這裏的BlogArticle對象的這竟然是問題的根源初始化:
- (id)initWithDictionary:(NSDictionary *)article
{
if (self = [super init])
{
// title = [[[article valueForKey:@"title"] gtm_stringByUnescapingFromHTML] copy];
// title = [[NSString alloc] initWithString:[[article valueForKey:@"title"] gtm_stringByUnescapingFromHTML]];
title = [[article valueForKey:@"title"] gtm_stringByUnescapingFromHTML];
}
return self;
}
所以每次的Objective-C編程誰也不像我這樣不討人喜歡告訴標題在分配之前從未被分配。如果我取消註釋上面兩行之一,它將起作用。程序崩潰什麼時候我嘗試初始化一個細胞與title變量,在這裏:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSLog(@"indexPath.row = %i", indexPath.row);
// Configure the cell.
BlogArticle *article = [allEntries objectAtIndex:indexPath.row];
cell.textLabel.text = article.title;
return cell;
}
現在,我需要明白的是爲什麼它編譯/工作不分配伊娃並在它到底會造成麻煩(或者標題內容的確切位置被釋放,導致程序崩潰)。 關於iOS環境中的內存管理的任何好資源(noob友好)將不勝感激。
感謝提前:)
無關你的問題,但是你似乎在'for'循環中泄漏了'blogArticle'Instances。 – 2011-03-30 13:44:37
至於內存管理,Apple的[文檔](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html#//apple_ref/doc/uid/20000043- BEHDEDDB)應該有你需要知道的一切。確保你真的瞭解「內存管理規則」部分。 – 2011-03-30 13:47:12
「泄漏」是什麼意思?分配內存並永不釋放它? – teum 2011-03-30 15:42:47