Reputation: 2488
I have a simple Answer class that looks like this:
@interface Answer : NSObject {
NSString *_text;
NSNumber *_votes;
}
@property(nonatomic, retain) NSString *text;
@property(nonatomic, retain) NSNumber *votes;
+(id)initFromAnswerData:(NSSet *)data;
-(id)initWithText:(NSString *)answer;
@end
The implementation looks like this:
#import "Answer.h"
#import "AnswerData.h"
#import "AppDelegate.h"
@implementation Answer
@synthesize text = _text;
@synthesize votes = _votes;
-(id)initWithText:(NSString *)answer {
if( (self=[super init])) {
_text = answer;
_votes = 0;
}
return self;
}
@end
If I create an array of Answers in a view controller using the initWithText:
method I inevitably have EXC_BAD_ACCESS errors when I take an Answer in the array and try to find it's text value.
However if I initialize a new Answer, set the text value and then add it to the array I don't have this access issue.
So this causes problems down the line:
[arrayOfAnswers addObject:[[Answer alloc] initWithText:@"Hello"]];
But this doesn't:
Answer *newAnswer = [[Answer alloc] initWithText:nil];
newAnswer.text = @"Hello";
[arrayOfAnswers addObject:newAnswer];
Can anyone explain why?
Upvotes: 4
Views: 2044
Reputation: 1
as you see , your
@property(nonatomic, retain) NSString *text; // this property is retain.
so the setter method of this should be- (void) setText:(NSString*)text{
[_text release];
_text = text;
[_text retain];
so when you call newAnswer.text = @"hello" ,it works, newAnswer holds the text.
but in your initWithText, there's no retain symbol, so sucks.
Upvotes: 0
Reputation: 161
You're using the attribute _text and _votes directly but not their setters. So, you're not retaining the input parameter answer for the line
_text = answer;
You should either change to
_text = [answer retain];
or
self.text = answer;
Upvotes: 5
Reputation: 11340
Are you retaining the array that you put your Answers
into? That would be my guess at what's wrong.
Upvotes: 1