EXC_BAD_ACCESS, when is a property set to a user class during initialization?

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?

+4
source share
3 answers

You use the _text and _votes attributes , but not their setters. This way you do not save the input parameter answer for the row

 _text = answer; 

You must either go to

 _text = [answer retain]; 

or

 self.text = answer; 
+5
source

Do you keep the array in which you put your Answers ? That would be my guess about what's wrong.

+1
source

as you can see, your @property (nonatomic, keep) NSString * text; // this property is saved. therefore, the setter method should be - (void) setText:(NSString*)text{ [_text release]; _text = text; [_text retain]; - (void) setText:(NSString*)text{ [_text release]; _text = text; [_text retain]; so when you call newAnswer.text = @ "hello" it works, newAnswer stores the text. but in your initWithText there is no save character, therefore sucks.

0
source

All Articles