NSCoding不起作用

时间:2012-04-27 10:26:59

标签: iphone objective-c ipad

我无法让NSCoding工作。我将一些数据保存到nsuserdefaults,然后尝试将其恢复。我确实得到了我正在保存的自定义类,但不是其中的变量。这是代码:

.h

   #import <UIKit/UIKit.h>

@interface Match : NSObject <NSCoding>
{
    NSString *player1Name; 
}

@property (nonatomic, strong) NSString *player1Name; 


@end

.m

#import "Match.h"

@interface Match ()

@end

@implementation Match

@synthesize player1Name;

#define player1NameKey @"player1NameKey"




- (id)initWithCoder:(NSCoder *)decoder
{

    if ((self = [super init]))
    {
         self.player1Name = [decoder decodeObjectForKey: @"asd"]; 
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder 
{
    [encoder encodeObject:self.player1Name forKey:@"asd"];
}

@end

功能:

Match *match = [[Match alloc] init]; 
match.player2Name = @"hi"; 


NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:[NSKeyedUnarchiver unarchiveObjectWithData: [defaults objectForKey: @"matches"]]]; 

[tempArray addObject:match];

NSData* arrayData = [NSKeyedArchiver archivedDataWithRootObject: tempArray];
[defaults setObject: arrayData forKey: @"matches"]; 


//Check if it succeded

NSMutableArray *tempArray2 = [[NSMutableArray alloc] initWithArray:[NSKeyedUnarchiver unarchiveObjectWithData: [defaults objectForKey: @"matches"]]]; 
Match *match2 = (Match *)[tempArray2 objectAtIndex:0];  

NSLog(@"match2: %@", match2.player2Name); 

我得到“匹配”对象,但变量“player2Name”为零。

请帮忙! 提前致谢

1 个答案:

答案 0 :(得分:2)

嗯,当然是。你永远不会在任何时候编码它。