某些NSCoding变量未被检索

时间:2012-10-16 11:58:40

标签: ios xcode nscoding

我正在使用NSData存储一个对象供以后使用。它有很多NSStrings,我需要将它从一个物体中拉出来 出于某种原因,只存储了NSStrings的 some ,其他一些被归零! 我认为它必须是我的代码,我必须忘记初始化一些字符串,但由于一个非常奇怪的原因,一些字符串会丢失数据! 我无法得到theImportantString得到它的相关值,因为它首先看起来变量得到了它的值,但是从Unarchive返回后,它等于@“”!

// CMyData.h
/////////////////////

@interface CMyData : NSObject <NSCoding>
{
    NSString *ID;
    NSString *DIST;
    .  
    .  
}
@property (nonatomic,retain) NSString *ID;
@property (nonatomic,retain) NSString *DIST;

@end

// CMyData.m
//////////////////////

#import "CMyData.h"
@implementation CMyData

@synthesize ID;
@synthesize DIST;

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.ID = [decoder decodeObjectForKey:@"ID"];
        self.DIST = [decoder decodeObjectForKey:@"DIST"];
    .  
    .  
 }


- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:ID forKey:@"ID"];
    [encoder encodeObject:DIST forKey:@"DIST"];
    .  
    .  

}

- (void)dealloc {
    [ID release];
    [DIST release];
    [super dealloc];

}

@end

MyController.m

-(void) makeObject: (NSDictionary *)dict
{    
    CMyData* myData=[[CMyData alloc] init];
    myData.ID = [[NSString alloc] initWithString:[dict objectForKey:@"NAME"]];
    myData.DIST = [[NSString alloc] initWithString:[dict objectForKey:@"DISTRIBUTOR"]];
    .  
    .  

    myObject = [[[MYObject alloc] init];

    myObject.data = [NSKeyedArchiver archivedDataWithRootObject:myData];
} 

然后按下按钮就会发生:

- (void) tapOnIcon: (MyObject*)theObject 
{
    CMyData *data = [NSKeyedUnarchiver unarchiveObjectWithData:theObject.data];
    [delegate showData:data];
}
委托控制器中的

(无法再设置值):

delegateController.m
/////////////////////////////////

-(void) showData:(CMyData*)theData{
     self.theImportantString = [[NSString alloc] initWithString:theData.DIST];
     .
     .
     .


}

1 个答案:

答案 0 :(得分:1)

似乎你的类型不匹配:

// in - (id)initWithCoder:(NSCoder *)decoder
self.DIST = [decoder decodeIntForKey:@"DIST"];

但在宣言中你有

// in CMyData.h
NSString *DIST;

这应该是:

// in - (id)initWithCoder:(NSCoder *)decoder
self.DIST = [NSString stringWithFormat:@"%d", [decoder decodeIntForKey:@"DIST"]];