2012-10-16 75 views
0

我正在使用NSData存儲對象以備後用。它有很多NSStrings,我需要將它從一個對象中拉出來。
由於某些原因,只有some的NSStrings被存儲,其他一些被清零! 我一直認爲它必須是我的代碼,我必須忘記初始化一些字符串,但出於一個非常奇怪的原因,一些字符串丟失了數據! 我無法得到theImportantString以得到它的相關值,因爲它首先看起來像變量得到它的價值,但從Unarchive回來後,它等於@「」!某些NSCoding變量未被檢索

// 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]; 
} 

再上一個按鈕公頃水龍頭ppens:

- (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]; 
    . 
    . 
    . 


} 
+0

爲什麼你使用'initWithString'時,你可以使用(串)對象本身?同樣,標識符「ID/DIST」和「NAME/DISTRIBUTOR」的使用也很混亂。 – trojanfoe

回答

1

看來你有不匹配的類型:

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

但declarati你有

// in CMyData.h 
NSString *DIST; 

這應該是:

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

我剛剛編輯的代碼是一個對象,錯誤輸入... – Ted

+0

好,如果你編碼nsstring和解碼對象這應該工作正常。 –

+0

你是說self.DIST應該是這樣的:self.DIST = [[NSString alloc] initWithString:[decoder decodeObjectForKey:@「DIST」]]; ? – Ted