2014-12-05 27 views
0

我知道這可能是一個天真的問題,但它對我來說是一個問題。現在我已經在applicationDidFinishLaunching中聲明瞭對象。如何使用此對象的applicationDidFinishLaunching 外如何使用這些對象在按鈕操作功能例如objective c如何從外部訪問applicationDidFinishLaunching變量

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 
// Insert code here to initialize your application 
AKanji *test2=[[AKanji alloc] init]; 
........ 
    } 



- (IBAction)kButton:(id)sender { 
    //iwant to access test 2 here 

    } 
+0

Wha t是面向對象代碼和實例變量的知識史嗎? – Wain 2014-12-05 09:46:13

+0

我對他們很陌生。對不起,我搜索了網絡機器人沒有找到任何答案 – 2014-12-05 09:48:47

+0

你應該閱讀https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011210-CH1-SW1,並通過https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210- CH5-SW2瞭解這部分 – Wain 2014-12-05 09:52:30

回答

0

AppDelegate.h,輸入您想創建實例

#進口文件AKanji.h

@interface AppDelegate : UIResponder 
@property(nonatomic, strong) AKanji *test2; 
@end 
在AppDelegate.m

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 
       // Insert code here to initialize your application 
       _test2 =[[AKanji alloc] init]; 
       ........ 
    } 

在ViewController.m

#import AppDelegate.h 

- (IBAction)kButton:(id)sender { 
    //iwant to access test 2 here 
    AppDelegate *delegate = [UIApplication sharedApplication].delegate; 
    // Now you can access using delegate.test2 

} 
-1

的AppDelegate類具有一個初始化爲任何其他類。 因此它可以有@properties。 因此,在init中,您可以對元素進行任何初始化,然後可以在整個類中使用。

+0

知道了,所以我必須聲明它們作爲屬性來訪問它們,哪裏是對的?非常感謝 – 2014-12-05 09:59:49

+0

hup @ AlaaAhmadM.Zakaria一般屬性是在課堂上可以訪問的變量。如果你把它們放在.m文件裏面(只在課堂內),如果你把它們放在外面.h – wolffan 2014-12-05 10:21:23

2

首先,您應該瞭解什麼是面向對象的編程語言及其正確使用。

現在來到您的問題部分。根本不可能在其他方法中訪問本地變量。一旦範圍/壽命結束,它就會被創建並被銷燬。 (在你的情況下,它是一個本地變量)

爲了達到這個目的,你需要使用一個ivar/property,在該方法中賦值,然後你可以在別處訪問它。

+0

aha我現在明白了。非常感謝 – 2014-12-05 10:02:11

0

我相信你必須在applicationDidFinishLaunching大括號之外移動你的Kanji * test2。你應該仍然可以在那裏分配/初始化它,如果這是你想要做的,你也可以在kButton中看到它。

+0

非常感謝我得到它我將它作爲財產 – 2014-12-05 10:04:22

+0

祝你好運。乾杯。 – hft 2014-12-05 10:05:54