gpt4 book ai didi

ios - 如何将NSArray保存到文件并从文件中检索NSArray

转载 作者:行者123 更新时间:2023-12-01 17:52:19 51 4
gpt4 key购买 nike

我一直在尝试执行is it possible to save NSMutableArray or NSDictionary data as file in iOS?给出的答案,但它们并未为我工作。有人可以告诉我我做错了什么吗?我的NSArray是一个自定义对象,例如Cat。猫本身由字符串和数字组成。这是我的代码

-(void)saveArrayToFile:(NSArray *)response;
{
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSString *filePath = [documentsDirectory stringByAppendingPathComponent:PERSISTENT_FILENAME];
//
// [response writeToFile:filePath atomically:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
if ([paths count] > 0)
{
// Path to save array data
NSString *arrayPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"array.out"];
// Write array
[response writeToFile:arrayPath atomically:YES];


}else NSLog(@"NO paths");
}

-(NSArray *)getArrayFromFile
{
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSString *filePath = [documentsDirectory stringByAppendingPathComponent:PERSISTENT_FILENAME];
// return [NSArray arrayWithContentsOfFile:filePath];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
if ([paths count] > 0)
{
// Path to save array data
NSString *arrayPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"array.out"];
NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath];
return arrayFromFile;
}else NSLog(@"No file to retrieve");
return nil;
}

首先,我尝试了注释的代码。然后我尝试了另一个。到目前为止的问题是该文件没有被保存。

最佳答案

保存时[以原子方式响应writeToFile:arrayPath:YES]返回false。因此它无法成功保存。尝试使用

Bool result = [NSKeyedArchiver archiveRootObject:response toFile:arrayPath];
NSArray *arrayFromFile = [NSKeyedUnarchiver unarchiveObjectWithFile:arrayPath];

在您的cat文件中:
@property(nonatomic, strong)NSString* score;
@property(nonatomic, assign)BOOL bGenuine;
@property(nonatomic, assign)NSInteger errorCode;

@synthesize score,bGenuine,errorCode;

- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:score forKey:@"score"];
[encoder encodeObject:[NSNumber numberWithBool:bGenuine] forKey:@"bGenuine"];
[encoder encodeObject:[NSNumber numberWithInt:errorCode] forKey:@"errorCode"];
}

- (id)initWithCoder:(NSCoder *)decoder {
score = [decoder decodeObjectForKey:@"score"];
bGenuine = [[decoder decodeObjectForKey:@"bGenuine"] boolValue];
errorCode = [[decoder decodeObjectForKey:@"errorCode"] integerValue];
return self;
}

关于ios - 如何将NSArray保存到文件并从文件中检索NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25777447/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com