2014-06-13 132 views
1

我有一個自定義對象類(Ship.h和Ship.m),我試圖創建一個新的船型對象與此代碼:對象的指針設置爲null後,對象的alloc和init

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

謝謝rmaddy!你非常有幫助! – inmysites

回答

2

有幾個問題。

  1. 你爲什麼在的@end語句後您的.h文件中聲明Ship *PlayerShip;?這使得它成爲一個全球變量。使其成爲像其他人一樣的實例變量,但將其置於@interface聲明的花括號中。
  2. viewDidLoad中,您將創建一個與(即將成爲)實例變量同名的局部變量。不要聲明新的變量。只需將新對象分配給(即將成爲)實例變量。