开发者

NSKeyedArchiver and description method : app crashes

i tried to test NSKeyedArchiver, but my code seems to be wrong. I then tried only with a NSLog, but the NSLog returns (null) if i alloc-init my var "model" in the init method (in the controller), and it makes the app crash if i put it in viewDidLoad.

Can someone have a look and tell me if something is wrong?

#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 "M开发者_Python百科odel.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


Your app is crashing because this line is wrong:

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

age is an int, not an object pointer. Needs to be:

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

I don't think there's anything obviously wrong with your encode/decode code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜