The problem is that you are not setting the value of the property var
in Class1
at the init method of this class. Yo do int only when button action
method is executed. So when you create a new instance of Class1
in your initWithNibName:bundle:
method in Class2
and access it (var2 = obj.var;
), this instance's var
property has not been set so it has a default nil
value.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
Class1 *obj = [[Class1 alloc] init];
var2 = obj.var; // <-- obj.var is not set, so it returns nil
NSLog(@"%@", var2);
//this print statement is (null)
}
return self;
}
In order to solve this, you could either initialize var
in Class1
at the init method or to have a reference to the same instance where you are running the buttonAction
to set the var value given to Class2
. For example, passing you Class1
instance as an input of your Class2
init method:
This is how you would create and initialized Class2
instance from buttonAction
method in Class1.m:
-(void)buttonAction:(UIButton*)sender;
{
self.var = @"some generated variable";
//after setting the variable I immediately call Class2
Class2 *obj2 = [Class2 alloc] initWithNibName:@"yourNibName"
bundle:nil
andClass1:self];
}
This would be your Class2
init method in Class2.m:
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
andClass1:(Class1 *)obj
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
var2 = obj.var; // <-- obj.var will be set in buttonAction
NSLog(@"%@", var2);
}
return self;
}