[英]Object pointer is set to null after object is alloc and init
我有一个自定义对象类(Ship.h和Ship.m),并且我正在尝试使用以下代码创建一个新的Ship类型对象:
Ship *PlayerShip = [[Ship alloc] init];
该代码当前在我的First view controller.m中
- (void)viewDidLoad{
但是我已经尝试过了
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
也一样
我创建了PlayerShip对象,没有任何问题,然后用
NSLog(@"Player ship: %@",PlayerShip);
它的日志也很好。
然后在代码的另一部分(我放置它的地方以外的地方),例如NSTimer,我尝试使用相同的NSLog行并返回
玩家飞船:空
是否出于某种原因删除了PlayerShip对象?
我将不胜感激任何帮助。
以下是我的shipViewController.h
#import <UIKit/UIKit.h>
#import "Ship.h"
@interface ShipViewController : UIViewController{
IBOutlet UILabel *PlayerShipLabel;
IBOutlet UIProgressView *PlayerHullBar;
IBOutlet UIProgressView *PlayerShieldBar;
IBOutlet UILabel *PlayerCreditsLabel;
IBOutlet UIImageView *PlayerShipImage;
IBOutlet UIButton *PlayerRepairBreachButton;
}
@end
Ship *PlayerShip;
这是ShipViewController.m
#import "ShipViewController.h"
@interface ShipViewController ()
@end
@implementation ShipViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
Ship *PlayerShip = [[Ship alloc] init];
NSLog(@"Player ship: %@",PlayerShip);
}
- (IBAction)ShieldSwitch:(id)sender {
NSLog(@"Ship is %@ ",PlayerShip);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
这是应用程序首次启动时程序的输出:
2014-06-12 19:02:27.503 First Game[5193:60b] Created a new ship!
2014-06-12 19:02:27.504 First Game[5193:60b] Player ship: <Ship: 0x8c30f70>
这是我按下按钮验证PlayerShip时的输出:
2014-06-12 19:02:29.472 First Game[5193:60b] Ship is (null)
有几个问题。
Ship *PlayerShip;
在@end
语句后的.h文件中? 这使其成为全局变量。 使其与其他实例变量一样,但将其放在@interface
语句的花括号中。 viewDidLoad
您将创建一个与(即将成为)实例变量同名的局部变量。 不要声明新变量。 只需将新对象分配给实例实例变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.