Objective-C:为什么我的NSString没有保留它的价值?

时间:2011-11-04 23:03:21

标签: objective-c nsstring

问题在于'initWithCoder'方法。当我想通过在我的'main'类中调用'saveData'方法从我保存它的地方检索“Coins_Key”并传入密钥“self.keyName”时,keyName的值为0。

//Class coins.h
@property (retain) NSString* keyName;
@property (retain) NSString* keyValue;

//Class coins.m
@synthesize keyName;
-(void) saveData:(NSString *)number: (NSString *)keyID 
{
    self.keyName = keyID;
    self.keyValue = number;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
     NSLog(@"Encoded keyName: %@", keyName);
    [encoder encodeObject:keyValue forKey:keyName];
}
- (id)initWithCoder:(NSCoder *)decoder {
    self.keyValue = [decoder decodeObjectForKey:self.keyName];
    NSLog(@"Decoded Coins: %@", self.keyValue);
    return self;
}

//Class main
[Coins *coin3 = [[Coins alloc] init];
[coin3 saveData:@"6" :@"Coins_Key"];        
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:coin3];
coin3 = [NSKeyedUnarchiver unarchiveObjectWithData:data];

1 个答案:

答案 0 :(得分:1)

您还没有完全掌握编码器/解码器的工作流程。

正确使用encodeObjectForKey:decodeObjectForKey:方法,您应该将用于存储值的作为参数传递。 此密钥必须保持不变。

您也不应要求呼叫者提供Coin对象用于存储数据的密钥。把这个简单的例子作为一个更正确/有效的方法(假设我理解你的类的目的):

// Class Coins.h

@property (assign) int numberOfCoins;

// Class Coins.m

#define NUM_COINS_KEY @"NUM_COINS_KEY"

@synthesize numberOfCoins;

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) { // Use [super initWithCoder:decoder] here if your superclass supports it
        self.numberOfCoins = [decoder decodeIntForKey:NUM_COINS_KEY];
        NSLog(@"Decoded Coins: %d", self.numberOfCoins);
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
     NSLog(@"Encoded keyName: %@", keyName);
    [encoder encodeInt:self.numberOfCoins forKey:NUM_COINS_KEY];
}

// Class main

Coins *coin = [[Coins alloc] init];
coin.numberOfCoins = 6;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:coin];
[coin release]; // If you're just playing around, this is probably overkill, but a good habit
coin = [NSKeyedUnarchiver unarchiveObjectWithData:data];