苦苦挣扎于全球变异阵营

时间:2014-04-02 03:44:47

标签: xcode nsmutablearray

我是iphone开发的新手。我试图使用持久数据并通过数组保存和加载它。当我在方法中使用了一个可变数组时它工作得很好,但是当我把它变成全局时我错过了一些东西,因为它不会在我的路径中创建data.plist。我尝试调试和跟踪数组但是当我尝试在buttonPressed上为它分配一个值时,它会显示一个大小为4的数组但没有值更改。当我有一个本地可变阵列时,这是有效的,现在我不知道我搞砸了什么。任何帮助赞赏。注意:这是针对学校的,所以请指导我正确的方向。

//
//  ViewController.h
//  Finances
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic, retain) NSArray *pickerData;
@property (nonatomic, retain) NSMutableArray *savedArray;

- (NSString *) filePath;
- (void) updateFile;
- (void) updateGraphics;
- (NSString *) formDollarString: (NSInteger *)variable;
- (IBAction)buttonPressed:(id)sender;

@end

以下是ViewController.m的相关部分,如果您需要或有疑问,请告诉我。

//  ViewController.m
//  Finances
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (NSString *)filePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}

- (void) updateFile {
    //Save Array
    [_savedArray writeToFile:[self filePath] atomically:YES];    
}

- (IBAction)buttonPressed:(id)sender {
    //Identify the button sender
    UIButton *btn = (UIButton *)sender;
    //Functions for reseting the program values.
    if ([btn.currentTitle isEqualToString:@"Reset"])
    {
        //Replaces all values with 0.
        for (NSInteger i =0; i < 4; i++){
            [_savedArray replaceObjectAtIndex:i withObject:@0];
        }
    }
    else
    {
        //Get the value of the picker.
        NSInteger row = [_singlePicker selectedRowInComponent:0];
        //Get integer value of the textbox.
        NSInteger value = [self.inputTextBox.text intValue];
        //Saves the value entered to the array.
        [_savedArray replaceObjectAtIndex:row withObject:@((value) + [[_savedArray objectAtIndex:row] integerValue])];
    }
    //Updates the array to the file.
    [self updateFile];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //Array for picker data information.
    NSArray *array = [[NSArray alloc] initWithObjects:@"Transportation",@"Food",@"Clothing",@"Entertainment", nil];
    self.pickerData = array;

    if([[NSFileManager defaultManager]fileExistsAtPath:[self filePath]]){
        _savedArray = [[NSMutableArray alloc]initWithContentsOfFile: [self filePath]];
    }
    else{
        NSMutableArray *newArray = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < 4; i++)
        {
            [newArray addObject:@0];
        }
    }

}

0 个答案:

没有答案