我试图学习如何使用 NSKeyedArchiver 保存对象数组,我编写了一个小应用程序来做到这一点,我登录查看数组是否已保存,但每次我得到 0 的数组计数,这里是代码。
视图控制器.h
@interface ViewController : UIViewController
{
IBOutlet UITextField *text;
IBOutlet UITextField *textName;
IBOutlet UITextField *textAge;
IBOutlet UILabel *name;
IBOutlet UILabel *age;
BOOL flag;
BOOL choice;
NSString *documentDirectory;
NSMutableArray *anArray;
Person *p;
NSData *data;
}
-(BOOL) dataFilePath;
-(IBAction)readPlist;
-(IBAction) writePlist;
@property (strong,nonatomic)IBOutlet UITextField *text;
@property (strong,nonatomic)IBOutlet UITextField *textName;
@property (strong,nonatomic)IBOutlet UITextField *textAge;
@property (strong,nonatomic)IBOutlet UILabel *name;
@property (strong,nonatomic)IBOutlet UILabel *age;
@property (strong,nonatomic)NSString *documentDirectory;
@property (strong,nonatomic)NSMutableArray *anArray;
@end
视图控制器.m
@interface ViewController ()
@end
@implementation ViewController
@synthesize text,documentDirectory,textAge,textName,name,age,anArray;
- (void)viewDidLoad
{
[super viewDidLoad];
// checking if the file was created and show a message if its created or not.
if ([self dataFilePath]) {
NSLog(@"File Created !");
} else {
NSLog(@"File Not Created !");
}
NSLog(@"File location : %@",documentDirectory);
choice = YES;
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL) dataFilePath
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentDirectory = [path objectAtIndex:0];
documentDirectory = [documentDirectory stringByAppendingPathComponent:@"MilmersData.dat"];
return TRUE;
}
- (IBAction)writePlist
{
p.name = textName.text;
p.age = [textAge.text intValue];
[anArray addObject:p];
for (int i=0; i<[anArray count]+1; i++) {
Person *pp = [[Person alloc]init];
pp=[anArray objectAtIndex:i];
NSLog(@"Name: %@",pp.name); // checking the names in pp object but getting null
}
data = [NSKeyedArchiver archivedDataWithRootObject:anArray];
[data writeToFile:documentDirectory options:NSDataWritingAtomic error:nil];
NSLog(@"Array length: %d",[anArray count]); //Always got array count zero.
}
-(IBAction)readPlist
{
NSString *filePath = documentDirectory;
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"The array is: %@",array); // it shows that there is nothing in the array
}
@end
我最初编写了用于编写 .plist 文件的类,但后来我知道我不能将对象存储在 .plist 文件中,所以我尝试使用存档,这就是方法名称中有 plist 的原因。
先感谢您