[英]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.