Reputation: 6096
I'm very new to Objective C.
I have a class PassageViewController. Here's the .h file:
#import <UIKit/UIKit.h>
@interface PassagesViewController : UIViewController {
UIButton *showPassagesButton;
UIButton *addButton;
UIView *passagesPanel;
}
@property (nonatomic, retain) NSMutableArray *titlesArray;
@property (nonatomic, retain) NSMutableArray *thePassages;
@end
In the .m file I have:
@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)
...
}
The initTestPassages method just fills thePassages with a bunch of different objects (using the method addObject
). This method isn't intended to be used in the finished app, I'm just playing around with thePassages to make sure I fully understand how it all works. (Which I don't.) The NSLog line in my viewDidLoad method tells me that thePassages contains the objets I want it to contain, at least at that point.
The problem is, when I try to access _thePassages from anywhere outside the above mentioned methods, the app crashes with the message EXC_BAD_ACCESS. For example, I created a method that contains the single line int i = [thePassages count]
and calling that method (e.g. by assigning it to one of the UIButtons on the screen crashes and gives the error.
I've had a look at similar questions and from what I can tell the problem is something to do with memory management, but this really isn't a topic I understand very well and I don't know where to start. What am I doing wrong?
Upvotes: 0
Views: 485
Reputation: 19030
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.
Upvotes: 4