0

私は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)。このメソッドは、完成したアプリで使用することを意図したものではありません。すべてがどのように機能するかを完全に理解するために、パッセージをいじっているだけです。(私はしません。) 私の viewDidLoad メソッドの NSLog 行は、少なくともその時点で、thePassages に含めたいオブジェクトが含まれていることを示しています。

問題は、上記の方法以外の場所から _thePassages にアクセスしようとすると、EXC_BAD_ACCESS というメッセージが表示されてアプリがクラッシュすることです。たとえば、単一行を含むメソッドを作成し、int i = [thePassages count]そのメソッドを呼び出します (たとえば、画面上の UIButtons の 1 つに割り当ててクラッシュし、エラーが発生します。

同様の質問を見てきましたが、問題はメモリ管理に関係していると言えますが、これは実際には私がよく理解しているトピックではなく、どこから始めればよいかわかりません。私は何を間違っていますか?

4

1 に答える 1

4

Change

thePassages = [NSMutableArray arrayWithCapacity:0];

to

self.thePassages = [NSMutableArray arrayWithCapacity:0];

Why?

The original line is setting the value directly, without going through the generated setter method. The setter method will retain the object for you, whereas when setting it directly you need to do that yourself. As such, you've assigned an autoreleased object to a variable, so whilst it's currently valid within the scope of viewDidLoad:, afterwards the object reference will become invalid when the instance is released and deallocated.

Bootnote: Have you considered switching to ARC? It would remove this sort of issue.

于 2013-02-05T17:32:56.670 に答える