xcode 如何使用 NSKeyedArchiver 对自定义类进行编码和解码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5768495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:53:55  来源:igfitidea点击:

How to encode and decode a custom class with NSKeyedArchiver

xcodememory-managementnskeyedarchivernscodingsaving-data

提问by Blane Townsend

I have a custom class that I wish to save and load. The class contains an NSDate, an NSString, and an NSNumber. I have implemented the NSCoding protocol in the .h file. Here is the code I have so far. theDate is an NSDate. theName is the NSString. homeAway is the NSNumber.

我有一个想要保存和加载的自定义类。该类包含一个 NSDate、一个 NSString 和一个 NSNumber。我已经在 .h 文件中实现了 NSCoding 协议。这是我到目前为止的代码。theDate 是一个 NSDate。theName 是 NSString。homeAway 是 NSNumber。

-(void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:theDate forKey:@"theDate"];
[aCoder encodeObject:theName forKey:@"theName"];
[aCoder encodeObject:homeAway forKey:@"homeAway"];
}

-(id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super init])) {
    theDate = [aDecoder decodeObjectForKey:@"theDate"];
    theName = [aDecoder decodeObjectForKey:@"theName"];
    homeAway = [aDecoder decodeObjectForKey:@"homeAway"];
}
return self;
}

I am using the code below to load my custom object. When I use print-object in the Debugger only the homeAway shows up as an actual object. theDate and theName say 0x4e4f150 does not appear to point to a valid object.

我正在使用下面的代码加载我的自定义对象。当我在调试器中使用打印对象时,只有 homeAway 显示为实际对象。theDate 和 theName 说 0x4e4f150 似乎没有指向有效的对象。

[gamesArray setArray:[NSKeyedUnarchiver unarchiveObjectWithFile:path]];  
Game *loadedGame = [gamesArray objectAtIndex:gameNumber];

I save the data using the following code:

我使用以下代码保存数据:

I use this to call my class to create a new Game (the custom class that I am trying to save). The code up to NSDate *aDate = [gameDate date]; is irrelevant.

我用它来调用我的类来创建一个新游戏(我试图保存的自定义类)。代码到 NSDate *aDate = [gameDate date]; 无关紧要。

-(void)newGame {
if (homeAway != 0) {
    if (dateChanged == 1) {
        if ([nameField.text length] > 0) {
            [homeButton setImage:[UIImage imageNamed:@"HomeGray.png"] forState:UIControlStateNormal];
            [awayButton setImage:[UIImage imageNamed:@"AwayGray.png"] forState:UIControlStateNormal];
            [dateButton setImage:[UIImage imageNamed:@"DateGray.png"] forState:UIControlStateNormal];
            [nameField setBackground:[UIImage imageNamed:@"textField.png"]];
            NSDate *aDate = [gameDate date];
            NSString *aString = [[[NSString alloc] initWithString:[nameField text]] autorelease];
            UIApplication *app = [UIApplication sharedApplication];
            [[[(miShotTrackAppDelegate *)[app delegate] viewController] courtViewOne] newGame:aDate withName:aString andPlace:homeAway];
            [loadTable reloadData];
            datePicke = 0;
            homeAway = 0;
            dateChanged = 0;
            nameField.text = @"";
            [self goBack];
            [self autoSave];
        }
    }
}

}

}

From that method I call the newGame method which is

从那个方法我调用了 newGame 方法,它是

-(void)newGame:(NSDate *)theDate withName:(NSString *)theName andPlace:(int)homeAway {

Game *newGame = [[Game alloc] init];
NSDate *tDate = [NSDate new];
tDate = theDate;
[newGame setTheDate:tDate];
NSString *tString = [NSString stringWithString:theName];
[newGame setTheName:tString];
NSNumber *theNumber = [NSNumber numberWithInt:homeAway];
[newGame setHomeAway:theNumber];
[gamesArray addObject:newGame];
gameNumber = [gamesArray count] - 1;
NSString *path = [self findGamesPath];
[NSKeyedArchiver archiveRootObject:gamesArray toFile:path];
[newGame release];
}

Why will my objects not save? Does copying my objects have something to do with it? I do get an error on the commented line that says "exc bad access". Please help...

为什么我的对象不会保存?复制我的对象与它有关吗?我确实在注释行上收到一个错误,上面写着“exc bad access”。请帮忙...

采纳答案by McCygnus

You're not implementing -initWithCoder correctly. -decodeObjectForKey returns autoreleased object. So the way you wrote the method, you're ending up with dangling pointers for all of your Game ivars. Change -initWithCoder to:

您没有正确实施 -initWithCoder。-decodeObjectForKey 返回自动释放的对象。因此,按照您编写方法的方式,您最终会得到所有 Game ivars 的悬空指针。将 -initWithCoder 更改为:

-(id)initWithCoder:(NSCoder *)aDecoder 
{
  if ((self = [super init])) {
    [self setTheDate:[aDecoder decodeObjectForKey:@"theDate"]];
    [self setTheName:[aDecoder decodeObjectForKey:@"theName"]];
    [self setHomeAway:[aDecoder decodeObjectForKey:@"homeAway"]];
  }
  return self;
}

and it should work for you.

它应该适合你。