我试图测试NSKeyedArchiver
,但我的代码似乎是错误的。然后我只尝试使用 a NSLog
,但NSLog
如果我在方法中(在控制器中)分配初始化我的 var “model”,则返回(null)init
,如果我将它放入,它会使应用程序崩溃viewDidLoad
。
有人可以看看并告诉我是否有问题吗?
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@class Model;
@interface AAViewController : UIViewController {
Model *model;
}
@property (nonatomic, retain) Model *model;
//+(BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;
@end
______
#import "AAViewController.h"
#import "Model.h"
@implementation AAViewController
@synthesize model;
- (id) init {
self = [super init];
if (self) {
model = [[Model alloc] initWithName:@"thomas" age:13];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
//self.model = [[Model alloc] initWithName:@"thomas" age:13];
NSLog (@"%@", self.model);
/*
if (![NSKeyedArchiver archiveRootObject:model toFile:@"test.archive"]){
NSLog (@"erreur");
[model release];
}
*/
NSLog(@"success !");
}
- (void)viewDidUnload {
//model = nil;
}
- (void)dealloc {
[model release];
[super dealloc];
}
@end
______
#import <Foundation/Foundation.h>
//@interface Model : NSObject <NSCoding>
@interface Model : NSObject {
NSString *name;
int age;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic) int age;
- (id) initWithName:(NSString *)theName age:(int)theAge;
/*
- (id) initWithCoder:(NSCoder *)encoder;
- (void) encodeWithCoder:(NSCoder *)decoder;
*/
@end
______
#import "Model.h"
@implementation Model
@synthesize name, age;
- (id) initWithName:(NSString *)theName age:(int)theAge {
self = [super init];
if (self) {
name = [theName copy];
age = theAge;
}
return self;
}
- (void) dealloc {
[name release];
[super dealloc];
}
/*
- (id) initWithCoder:(NSCoder *)decoder{
self = [super init];
if (self) {
name = [[decoder decodeObjectForKey:@"nom"] retain];
age = [decoder decodeIntForKey:@"age"];
}
return self;
}
- (void) encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:name forKey:@"nom"];
[encoder encodeInt:age forKey:@"age"];
}
*/
- (NSString *) description {
return [NSString stringWithFormat:@"the name is : %@, %@ years old", name, age];
}
@end