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.
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];
}
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.