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 is as follows:
#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 responses in the view controller using the initWithText: , I inevitably get EXC_BAD_ACCESS errors when I take the Answer in the array and try to find its text value.
However, if I initialize a new answer, set the text value and then add it to the array. I do not have this access problem.
Thus, this causes problems in the line:
[arrayOfAnswers addObject:[[Answer alloc] initWithText:@"Hello"]];
But this is not so:
Answer *newAnswer = [[Answer alloc] initWithText:nil]; newAnswer.text = @"Hello"; [arrayOfAnswers addObject:newAnswer];
Can someone explain why?
source share