gpt4 book ai didi

ios - 在对象被分配和初始化后,对象指针被设置为空

转载 作者:行者123 更新时间:2023-11-29 10:41:46 25 4
gpt4 key购买 nike

我有一个自定义对象类(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 行并返回

Player Ship: Null

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) 

最佳答案

有几个问题。

  1. 为什么在 @end 语句之后在 .h 文件中声明 Ship *PlayerShip;?这使它成为一个全局变量。使它像其他变量一样成为实例变量,但将其放在 @interface 语句的花括号中。
  2. viewDidLoad 中,您创建了一个与(即将成为的)实例变量同名的局部变量。不要声明新变量。只需将新对象分配给(即将成为的)实例变量。

关于ios - 在对象被分配和初始化后,对象指针被设置为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24196625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com