NSMutablearray计数给出EXC_BAD_ACCESS

时间:2013-02-05 17:30:06

标签: objective-c nsmutablearray

我对Objective C很新。

我有一个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)。这个方法不适合在完成的应用程序中使用,我只是在使用thePassages来确保我完全理解它是如何工作的。 (我没有。)我的viewDidLoad方法中的NSLog行告诉我,thePassages包含我希望它包含的对象,至少在那时。

问题是,当我尝试从上述方法之外的任何地方访问_thePassages时,应用程序崩溃并显示消息EXC_BAD_ACCESS。例如,我创建了一个包含单行int i = [thePassages count]并调用该方法的方法(例如,通过将其分配给屏幕上的其中一个UIButton崩溃并给出错误。

我已经看过类似的问题了,从我能说出来的问题是与内存管理有关,但这真的不是我理解的主题,我不知道从哪里开始。我做错了什么?

1 个答案:

答案 0 :(得分:4)

更改

thePassages = [NSMutableArray arrayWithCapacity:0];

self.thePassages = [NSMutableArray arrayWithCapacity:0];

<强>为什么吗

原始行直接设置值,而不通过生成的setter方法。 setter方法将为您保留对象,而在直接设置时,您需要自己完成。因此,您已为变量分配了一个自动释放的对象,因此当它在viewDidLoad:范围内有效时,之后在释放和释放实例时对象引用将变为无效。

Bootnote:您是否考虑过切换到ARC?它会消除这类问题。

相关问题