ios - 将值设置为另一个类的属性的类对象 - Objective c

标签 ios objective-c xcode

我很难表达我的问题,所以我会写一个简单的例子。我有 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/

相关文章:

iOS 多 Collection View

ios - 在 iOS7 上播放视频流

IOS - 使用 Youtube API 检查 Youtube 视频是否存在

iphone - UIBezierPath 路径太多 = 太慢?

xcode - iOS应用程序中确实需要MainWindow.xib吗?

ios - 如何在 icarousel ios 中找到特定的索引?

ios - 圆几何上的点

objective-c - 如何使用 Swift 中的 AXUIElementCopyAttributeValue?

ios - Xcode 11 向后兼容性 : "UIWindowScene is only available in iOS 13 or newer"

ios - 如何以编程方式从堆栈中删除 UViewController