Search code examples
iosxcodesaving-data

Save value of the variables in file xcode ios


I have an example of saving date of taxtfield

- (NSString *) getFilePath {
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [[pathArray objectAtIndex:0] stringByAppendingPathComponent:@"saved.plist"];
}

 -(void) saveData {
    NSArray *value = [[NSArray alloc] initWithObjects:[myTextField text],nil];
    [value writeToFile:[self getFilePath] atomically:YES];
}

but how I can save value of the variables in file?

NSInteger = record1, record2;

Solution

  • NSInteger is not an Objective-C type, but you can convert it to NSNumber to store it in an array (or dictionary):

    NSInteger record1 = 17, record2 = 23;
    NSNumber *number1 = [NSNumber numberWithInteger:record1];
    NSNumber *number2 = [NSNumber numberWithInteger:record2];
    

    Starting with Xcode 4.4, you can also use the "Boxed Expression" syntax:

    NSNumber *number1 = @(record1);
    

    Now you can put the numbers into an array:

    NSArray *arrayToSave = [[NSArray alloc] initWithObjects:number1, number2, nil];
    [arrayToSave writeToFile:[self getFilePath] atomically:YES];
    

    You should also consider using a dictionary instead of an array to store the various values, for example (using boxed expressions again):

    NSDictionary *dictToSave = @{
        @"value1" : number1,
        @"value2" : number2,
        @"textField" : [myTextField text]
    };
    [dictToSave writeToFile:[self getFilePath] atomically:YES];