Objective c 传递对象时数据丢失

Objective c 传递对象时数据丢失,objective-c,pass-by-reference,pass-by-value,nscopying,pass-by-pointer,Objective C,Pass By Reference,Pass By Value,Nscopying,Pass By Pointer,我有一个目标 @interface QuestionViewModel : NSObject @property (nonatomic, assign) NSInteger questionId; @property (nonatomic, strong) NSString *questionText; @property (nonatomic, assign) NSInteger questionNumber; @property (nonatomic, strong) NSArray *c

我有一个目标

@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
我知道当我填充这个对象时,它是成功的,并且所有属性都被完全正确地初始化

但是,当我像这样通过此对象时:

- (id)init {
    if((self = [super init])) {
        // Set whatever init parameters you need here
    }
    return self;
}
*这是另一个类(不在上面定义的NSObject中)

question.nextQuestion
question.previousQuestion
nil

为什么当我传递此对象时,后续对象(nextQuestion和previousQuestion)变为零?虽然不确定,但该对象似乎正在进行浅拷贝而不是深拷贝


似乎有一些基本的东西我不知道。

我想你需要先初始化你的子类
问题视图模型
NSObject。在
QuestionViewModel.m
文件中,可以覆盖init方法。大概是这样的:

- (id)init {
    if((self = [super init])) {
        // Set whatever init parameters you need here
    }
    return self;
}
然后,在尝试使用此方法的类中,只需调用:

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

我最终改变了模型,使其更接近于链表。当我存储上一个和下一个对象时,它非常接近,但我最终更改了上一个和下一个属性来存储对象的索引,而不是实际对象

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

我实现了这一点,但它并没有产生任何影响。这些属性仍在变为零。不过修复的尝试不错。对象根本没有被复制<代码>问题指向一个问题,该指针被分配到
当前问题
。签入
nextQuestion
self.currentQuestion,
self.currentQuestion.nextQuestion
self.currentQuestion.nextQuestion
的值为零。self.currentQuestion.nextQuestion对列表中的第一个问题有效,但对所有其他问题无效。我认为,您正在创建与self(QuestionViewModel)相同类型的对象的属性(nextQuestion,previousQuestion)这一事实正在创建某种递归问题。这是一种令人困惑的策略。是否最好将nextQuestion和previousQuestion存储为单独的类实例,并在实例化它们的任何类中相应地更新它们?不,将nextQuestion和previousQuestion存储为单独的类实例不是一个好主意。指向同一类的另一个实例是可以的。所有问题都初始化正确吗?他们是否指向下一个和上一个问题?我认为你没有正确设置下一个和上一个问题。你不仅仅会丢失数据。对象的地址作为参数传递时不会更改。您确实存储了地址<代码>问题视图模型*是一个指针。