Saifee Saifee - 5 months ago 9
Objective-C Question

code works fine on emulator but getting nil on real device

this code is working fine and i get button while i test this code on emulator but I get nil when I test the on real device.

button is declared in header file interface

@property (weak, nonatomic) UIButton *button;


then it is synthesized in implementation file

@synthesize button;


then in a function call i am doing this

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

screenHeight = screenHeight - 135;

//Call
button = [UIButton buttonWithType:UIButtonTypeCustom];


when i run this code on real device (iphone 5) the button is always nil. I have noticed while debugging that after running last line
the execution goes back to

CGFloat screenHeight = screenRect.size.height;


and starts again, by the way there is no loop code here.. I cant understand this phenomena. what am i missing here.

Answer

You have a weak reference to your button, so it's getting deallocated before you add it as a subview. You can either change it to have a strong reference:

@property (nonatomic, strong) UIButton *button;

Or keep a reference to the button while you add it to your view:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:myButton];
_button = myButton;

It is now retained by the view so won't get released.