作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直在尝试执行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];
@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/
我是一名优秀的程序员,十分优秀!