I'm new at iPhone development and was practicing a bit. I connected a uilabel I made through IB to an IBOutlet in my code as many tutorials said but upon trying to set text of it it's still saying it's null? I defined the IBOutlet object on 开发者_JS百科my .h class and connected it fine through IB without a problem but idk why it's still null. Any help would be greatly appreciated.
Okay, first things first, let's remove some of the extraneous stuff and focus on the core of what you need.
#import "CalculatorBrain.h"
@interface CalculatorViewController : UIViewController
{
CalculatorBrain* _calculatorModel;
UILabel *display;
}
- (IBAction) digitPressed:(UIButton *)sender;
@property (nonatomic, retain) IBOutlet UILabel *display;
@end
#import "CalculatorViewController.h"
@implementation CalculatorViewController
@synthesize display;
- (void)dealloc
{
[display release], display = nil;
[_calculatorModel release];
[super dealloc];
}
- (void)viewDidLoad
{
[super viewDidLoad];
if (! _calculatorModel)
{
_calculatorModel = [[CalculatorBrain alloc] init];
}
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"display is: %@", display);
}
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *currentDigit = [[sender titleLabel] text];
[display setText:[NSString stringWithFormat:@"%@", currentDigit]];
}
@end
Let us know what happens when you've set the label (display) and the action (digitPressed:) in InterfaceBuilder.
Try changing your property to copy (or retain, but copy is more idiomatic for this situation):
@property (copy) IBOutlet UILabel *display;
Your assign
property is not incrementing the reference count for the string, thus there is no guarantee that it will still exist by the time you need it.
精彩评论