Take the 2-minute tour ×

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;


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;


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?

share|improve this question
NSNumber is a class. Use [NSNumber numberWithInt:0] –  David Rönnqvist Aug 17 '12 at 15:41
this may be dumb, but you are in fact allocated and initializing arrayOfAnsers, right? I would guess you are since you can successfully add an object, even if it's not the way you want to. Need to ask though –  achi Aug 17 '12 at 15:55

3 Answers 3

up vote 2 down vote accepted

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];


self.text = answer;
share|improve this answer
This is it. Brilliant, thanks. Huge oversight on my part. –  John H Sep 3 '12 at 15:54

Are you retaining the array that you put your Answers into? That would be my guess at what's wrong.

share|improve this answer

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.

share|improve this answer

Your Answer


