NSKeyedArchiver和描述方法:app崩溃

时间:2011-09-07 13:30:38

标签: objective-c nskeyedarchiver

我试图测试NSKeyedArchiver,但我的代码似乎错了。然后我只尝试使用NSLog,但NSLog返回(null),如果我在init方法(在控制器中)中分配init我的var“model”,它会使如果我把它放在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

1 个答案:

答案 0 :(得分:2)

您的应用正在崩溃,因为此行错误:

return [NSString stringWithFormat:@"the name is : %@, %@ years old", name, age];

age是一个int,而不是一个对象指针。需要:

return [NSString stringWithFormat:@"the name is : %@, %d years old", name, age];

我认为您的编码/解码代码没有任何明显错误。