2013-02-03 69 views
0

我想在我的視圖控制器中的多個方法中使用一個變量整數。 secondsLeft變量工作正常,但otherNumber變量不起作用。我得到的錯誤:初始化元素不是編譯時常量。任何想法,我應該如何做到這一點?謝謝!全局變量從應用程序代理拉

@interface ViewController() 

@end 

@implementation ViewController 
@synthesize countDown,Timerlbl; 

int secondsLeft = 500; 

int otherNumber =[(AppDelegate *)[UIApplication sharedApplication].delegate otherNumber]; 

回答

2

的問題是,您已聲明otherNumber爲全局變量和編譯器期望的初始分配是一個編譯期時間常數。 [delegate otherNumber]導致選擇器調用,這不是一個編譯時常量。

解決方案是將任務移到代碼中。例如:

- (id)init 
{ 
    self = [super init]; 
    if(self) { 
     otherNumber = [(AppDelegate *)[UIApplication sharedApplication].delegate otherNumber]; 
    } 

    return self; 
} 

作爲另一個說明,全局變量在Objective-C中通常是不可取的。通常更推薦使用@property值。不僅如此,你的ViewController類現在依賴於你的AppDelegate。由於您的AppDelegate最有可能是負責實例化您的ViewController,因此請考慮將其注入的值爲otherNumber。例如:

@interface ViewController() 
@property (nonatomic, assign) int otherNumber; 
@end 

- (id)initWithSomeNumber:(int)otherNumber 
{ 
    self = [super init]; 
    if(self) { 
     self.otherNumber = otherNumber; 
    } 

    return self; 
} 
+0

謝謝!相反,我正在使用@property方式。 – Brandon

+0

如何獲取應用程序委託來注入值 - 此代碼是否在我的應用程序委託中? – Brandon

+0

在你的應用程序委託中,當實例化你的'ViewController'時,像這樣'viewController = [[ViewController alloc] initWithSomeNumber:23849];'。你需要在'ViewController'的公共'@interface'中公開'initWithSomeNumber'' –

0

我認爲AppDelegate是您的應用程序委託類的名稱?

你有沒有嘗試添加導入您的AppDelegate,像這樣...

#import "AppDelegate.h" 

@interface ViewController() 
0

你不能聲明一個變量是這樣,因爲編譯器不能創建的AppDelegate一個實例,並要求它的otherNumber值應該是什麼。

根據使用方式的不同,最好不要定義otherNumber變量,而是在每次使用時從AppDelegate中檢索它。這可能意味着多一點打字,但它意味着你將永遠得到otherNumber

而且最新的正確值,這是一般的好主意定義整型變量時使用NSInteger而不是int