Data Loss When Passing Object

109 Views Asked by At

I have an object

@interface QuestionViewModel : NSObject

@property (nonatomic, assign) NSInteger questionId;
@property (nonatomic, strong) NSString *questionText;
@property (nonatomic, assign) NSInteger questionNumber;
@property (nonatomic, strong) NSArray *choices;

@property (nonatomic, strong) QuestionViewModel *nextQuestion;
@property (nonatomic, strong) QuestionViewModel *previousQuestion;

@end

I know when I populate this object it is successful and all properties are initialized fully and correctly.

However, when I pass this object like this:

*This is a different class (it is not in the NSObject defined above).

@property (nonatomic, strong) QuestionViewModel *currentQuestion;

- (void)nextQuestion
{
    [self loadQuestion:self.currentQuestion.nextQuestion];
}

- (void)loadQuestion:(QuestionViewModel *)question
{
    self.currentQuestion = question;
    .
    .
    .
}

question.nextQuestion and question.previousQuestion are nil.

Why when I pass this object do the subsequent objects (nextQuestion and previousQuestion) become nil? It seems like the object is doing a shallow copy rather than a deep copy, not sure though.

It seems like there is something foundational that I do not know about.

2

There are 2 best solutions below

1
Bohm On

I think you need to initialize your sub-classed QuestionViewModel NSObject first. In the QuestionViewModel.m file you can override the init method. Something like this:

- (id)init {
    if((self = [super init])) {
        // Set whatever init parameters you need here
    }
    return self;
}

Then, in the class where you are trying to use this method simply call:

-(void)viewDidLoad {
    QuestionViewModel *currentQuestion = [[QuestionViewModel  alloc] init];
}
1
tentmaking On

I ended up changing the model to more closely reflect a Linked List. It was close as I was storing previous and next objects, but I ended up changing the previous and next properties to store the index of the object, instead of the actual object.

@property (nonatomic, assign) NSInteger nextQuestionIndex;
@property (nonatomic, assign) NSInteger previousQuestionIndex;