2013-02-05 50 views
0

我很新的Objective CNSMutable array count給EXC_BAD_ACCESS

我有一個類PassageViewController。這裏的.h文件:

#import <UIKit/UIKit.h> 

@interface PassagesViewController : UIViewController { 
    UIButton *showPassagesButton; 
    UIButton *addButton; 

    UIView *passagesPanel; 
} 

@property (nonatomic, retain) NSMutableArray *titlesArray; 
@property (nonatomic, retain) NSMutableArray *thePassages; 

@end 

在.m文件我有:

@implementation PassagesViewController 

@synthesize thePassages; 

- (id) init { 
    if (self = [super init]) { 

     self.title = @"Passages"; 

    } 
    return self; 
} 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
// Do any additional setup after loading the view. 

    thePassages = [NSMutableArray arrayWithCapacity:0]; 

    [self initTestPassages]; 
    NSLog("%@", [thePassages description]); 

    ... 
    (Code to lay out the buttons etc on screen, as I'm not using a xib file) 
    ... 
} 

的initTestPassages方法剛好充滿thePassages與一羣不同對象(使用方法addObject)的。這個方法並不打算在完成的應用程序中使用,我只是在玩弄這些消息以確保我完全理解它是如何工作的。 (我不這樣做。)我的viewDidLoad方法中的NSLog行告訴我,該消息包含我希望它包含的objets,至少在那個時候。

問題是,當我嘗試從上述方法之外的任何地方訪問_thePassages時,該應用程序崩潰並顯示消息EXC_BAD_ACCESS。例如,我創建了一個方法,其中包含單行int i = [thePassages count]並調用該方法(例如,通過將其分配給屏幕上的某個UIButtons崩潰並給出錯誤信息)

我已經看過類似的問題,從我可以告訴問題是關於內存管理,但這真的不是一個話題,我的理解非常好,我不知道從哪裏開始。我在做什麼錯了?

回答

4

更改

thePassages = [NSMutableArray arrayWithCapacity:0]; 

self.thePassages = [NSMutableArray arrayWithCapacity:0]; 

爲什麼?

原始行直接設置值,而不通過生成的setter方法。 setter方法將爲您保留該對象,而直接設置它時,您需要自己做。因此,您已將自動釋放對象分配給變量,因此當它在viewDidLoad:範圍內當前有效時,此時在釋放和釋放實例時對象引用將變爲無效。

備忘錄:您是否考慮切換到ARC?它會消除這類問題。

+1

這就是爲什麼ivars應該有前導下劃線。它消除了這類錯誤。而不是@ @synthesize thePassages;',使用@synthesize thePassages = _thePassages;'。這就是自動合成所做的。看到[這個問題](http://stackoverflow.com/questions/14115774/why-does-xcode-automatically-create-variables-with-underscores)。 – SSteve

+0

或者完全刪除'@ synthesize'。 – bbum

+0

它的工作原理!謝謝。接受了你們兩個的建議,並將'thePassages'改爲'self.thePassages'和'合成了這個消息;'改成'@synthesize thePassages = _thePassages'。 我不知道ARC是什麼......但我會研究它。 – GMA