简体   繁体   中英

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;

另外,如果您不想写入特定文件,请使用– setInteger:forKey:– integerForKey:方法检查NSUserDefaults类以存储和检索整数值。

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM