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?
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
You should either change to
or