2012-08-25 54 views
1

我需要定義一個數組作爲全局變量,我可以使用它遍及我的代碼數組必須有一個數據爲10個隨機數,必須在代碼中修復我所做的有下列但在@interface之後.h文件沒有運氣 我把這個線定義數組作爲全局變量在目標c

NSMutableArray *globalarray; 

,並在.m文件我把這個@implemention文件後

- (void)glo { 
if (!globalarray) { 
globalarray= [NSMutableArray globalarray]; 
    for (int x = 0; x < 10; x++) { 
     [globalarray addObject:[NSNumber numberWithInt: arc4random()%200]]; 
    }}} 

和在同一個.m文件我調用NSLOG中的數組,如下所示

-(IBAction)click_one:(id)sender{ 


    NSLog(@"%@",globalarray);} 



-(IBAction)click_two:(id)sender{ 


    NSLog(@"%@",globalarray);} 

的的NSLog在控制檯任何幫助高度apprectaied感謝

+1

將'[self glo];'設置爲'init'或'viewDidLoad'方法 – beryllium

+0

我可能是錯的,但我敢肯定你應該在頭文件中聲明對象爲'extern'並且把真實聲明在源文件中。 – mk12

+0

謝謝,但我收到下面 –

回答

3

此行返回null:

globalarray= [NSMutableArray globalarray]; 

假定有上NSMutableArray的一些方法被稱爲 「globalarray」。沒有。你想:

globalarray = [[NSMutableArray alloc] init]; 
+0

多數民衆贊成在完美的作品罰款很多很多謝謝:) –

0
#import "AppDelegate.h" 

// in viewDidLoad 
self.del = (AppDelegate*) [[UIApplication sharedApplication] delegate]; 

// array now available as 
NSLog(@"%@", del.dataArray); 
0

問題是你分配自動釋放分配。

GlobalArray=[NSMutableArray array]; is same declarating it as. 

    GlobalArray=[[[NSMutableArray alloc]init]autorelease]; 

//所以在這裏分配和標記它自動釋放時1引用計數增加使得引用計數爲0。它的引用計數爲0則選擇了垃圾收集,所以你需要保留它,就像這

GlobalArray=[[NSMutableArray array]retain];// when retaining its reference count increases by 1 

需要時釋放它。