TJ15
TJ15

Reputation: 363

Saving int values to Array when app closes

I have an Iphone app that uses alot of int values that will increment on IBActions, I want to save the int values to an array when the app closes so that these values are stores and used when the app is reopened. I am not sure how to write int values into an array. Functionally, I am getting this to wort with text field but not integers i.e.

int count;

code used:

NSArray *values = [[NSArray alloc] initWithObjects:fieldOne.text,fieldTwo.text,count, nil];

This gives an "Assignment makes integer from pointer without cast" message.

Is there anyway to write already stored int values into and array? code I used is as follows:

I thinks its ok until the calling the data into the array. I have commented out some failed efforts

-(NSString *) saveFilePath{

    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    return [[path objectAtIndex:0] stringByAppendingPathComponent:@"savefile.plist"];
}


-(void) applicationDidEnterBackground: (UIApplication *) application{
    //NSNumber *num = [[NSNumber alloc]initWithInt:count];
    NSArray *values = [[NSArray alloc] initWithObjects:fieldOne.text,fieldTwo.text,[NSNumber numberWithInt:count],nil];
    [values writeToFile:[self saveFilePath] atomically:YES];
    [values release];

}

- (void)viewDidLoad {

    //NSNumber *num = [[NSNumber alloc]initWithInt:count];
    NSString *myPath = [self saveFilePath];

    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
    if (fileExists) {
        NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
        fieldOne.text = [values objectAtIndex:0];
        fieldTwo.text = [values objectAtIndex:1];
        //[NSNumber count intValue] = [values objectAtIndex:2];
        [values release]; 
    }


    UIApplication *myApp = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (applicationDidEnterBackground:)name:UIApplicationDidEnterBackgroundNotification object:myApp];


     [super viewDidLoad];
}

Thank you for your help.

Upvotes: 0

Views: 434

Answers (3)

Martin
Martin

Reputation: 747

You should use NSNumber so something like:

NSNumber *num = [NSNumber numberWithInt:int];

which will give you an object containing your int. To read back from it, use [num intValue]

Upvotes: 2

hburde
hburde

Reputation: 1441

Container classes work with Objects not fundamental types. You have to wrap fundamental types in NSNumber (numbers) , NSData etc.

Upvotes: 0

Phillip Mills
Phillip Mills

Reputation: 31016

Create a NSNumber object with your count as its value and put the object into your array. NSArrays need to be arrays of objects.

Upvotes: 0

Related Questions