我很难表达我的问题,所以我会写一个简单的例子。我有 2 个类,MyclassA 和 MyclassB。
@interface MyclassA
@property (nonatomic, assign) int *ID;
@property (nonatomic, strong) MyclassB *secondclass;
@end
@implementation MyclassA
-(id)init
{
self.ID = 1;
MyclassB *sec = [[MyclassB alloc] init];
sec.age = 10;
sec.weight = 35;
self.secondclass = sec;
return self;
}
MyclassB:
@interface MyclassB
@property (nonatomic, assign) int age;
@property (nonatomic, assign) int weight;
@end
当我在
下放置断点时return self;
self.secondclass 的值为 null。
我做错了什么?
最佳答案
您正在创建 MyClassB
的新对象。您应该在 init
方法中初始化属性 secondClass
而不是分配 MyClassB
的另一个实例的引用。
-(id)init
{
self.ID = 1;
self.secondclass = [[MyclassB alloc] init];
self.secondclass.age = 10;
self.secondclass.weight = 35;
return self;
}
关于ios - 将值设置为另一个类的属性的类对象 - Objective c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43736328/