2017-03-12 43 views
-4

對於我的iOS應用程序我想啓動一個NSMutableArray,並在運行時用按鈕更改數組保存的對象。到目前爲止,我能夠在ViewController.m中的viewDidLoad {}中啓動一個數組,但現在我無法在我的buttonPressed方法中訪問它。我怎樣才能讓數組訪問保存文件?如何在按下按鈕時在NSMutableArray中添加值

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 
    NSMutableArray *toCalculate = [@[@0] mutableCopy]; 
} 


- (IBAction)numbersButtonsPressed:(UIButton *)sender { 
    NSLog(@"%ld\n", sender.tag); 
    [toCalculate addObject:[NSNumber numberWithLong:sender.tag]]; 
} 
+1

請把你的代碼中的問題,而不是一個屏幕截圖。您需要將數組聲明爲屬性,而不是'viewDidLoad'中的局部變量 – Paulw11

回答

0

聲明變量爲全局(類變量)不是局部變量(函數)。

What is global variable?

解決方案的問題是:

#import "ViewController.h" 

@interface ViewController(){ 
    NSMutableArray *toCalculate; 
} 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    toCalculate = [@[@0] mutableCopy]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 



- (IBAction)numbersButtonsPressed:(UIButton *)sender { 
    NSLog(@"%@",toCalculate); 
    [toCalculate addObject:[NSNumber numberWithLong:sender.tag]]; 
} 


@end 
0

感謝保羅, 它的工作,如果你實現它作爲ViewController.h文件@property他說的那樣。

@interface ViewController: UIViewController 

    @propety NSMutableArray *giveItAName 

    @end 
相關問題