我有一个自定义对象类(Ship.h和Ship.m),我正在尝试使用以下代码创建一个新的Ship类型对象:
Ship *PlayerShip = [[Ship alloc] init];
代码目前在我的第一个视图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)
答案 0 :(得分:2)
有几个问题。
Ship *PlayerShip;
声明之后在.h文件中声明@end
?这使它成为一个全局变量。使其成为与其他变量类似的实例变量,但将其置于@interface
语句的大括号中。viewDidLoad
中,您创建一个与(即将成为)实例变量同名的局部变量。不要声明一个新变量。只需将新对象分配给(即将成为)实例变量。