student
student

Reputation: 179

Set value to a class object which is property of another class - Objective c

It's difficult for me to express my problem so I will write a simple example of it. I have 2 classes, MyclassA and 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

When I place a breakpoint at

return self;

the value of self.secondclass is null.

What am I doing wrong?

Upvotes: 1

Views: 1465

Answers (3)

Jitendra Solanki
Jitendra Solanki

Reputation: 772

You are creating a new object of the MyClassB. You should initialize the property secondClass in the init method instead of assigning the reference of another instance of MyClassB.

-(id)init
{
  self.ID = 1;
  self.secondclass = [[MyclassB alloc] init];
  self.secondclass.age = 10;
  self.secondclass.weight = 35;

  return self;
}

Upvotes: 1

Bhumesh Purohit
Bhumesh Purohit

Reputation: 499

 self.secondclass = [[MyclassB alloc] init];

Assign Properly

Upvotes: 0

KKRocks
KKRocks

Reputation: 8322

replace this line

MyclassB *sec = [[MyclassB alloc] init];

With

self.secondclass  = [[MyclassB alloc] init];

Upvotes: 0

Related Questions