2016-10-23 4 views
0

以下の2つの問題について助言してください。NSKeyedUnarchiverファイルにデータが存在しても、一部の属性のnilを読み取る

  1. 私は、データの一部がデータがplistファイルをアーカイブ解除方法を助言するfile.Pleaseに存在しているにもかかわらず、ゼロとして来ているfile.Butの内容を読み取るには、以下のコマンドを使用しています。

    @property NSDecimalNumber *miles 
    

    私は

    self.miles = [coder decodeObjectForKey:@"miles"] 
    
    initWithCoder方法で

    [aCoder encodeObject:_miles forKey:@"miles"] 
    
    のように書いています:ラインのために

    Dealer *dealer=[[NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/Documents/dealer.plist"] retain]; 
    
  2. encodeWithCoderの方法では、

    である。

ただし、データはplistファイルに保存されません。お知らせ下さい。

+0

。合成されたアクセサメソッドが適切なメモリ管理を行うためには、適切な修飾子を実際に含めるべきです。静的解析(Xcodeの "Product"メニューの "Analyze")を行うと、このような問題が警告されます。または、ARCを使用すると、あなたの人生がずっと楽になります。 – Rob

答えて

0

観測のカップル:

  • あなたはそのようなハードコーディングされたパスを使用しないでください。アプリケーションのドキュメント、キャッシュ、または一時フォルダ内のパスを使用する必要があります。

  • 戻りコードarchiveRootObjectを確認しましたか?それは成功しましたか?

しかしencodeObject:forKey:decodeObjectForKey:呼び出しでは何も問題はありません。次のコードは私のためにうまくいきました。問題がパスでない場合、問題は他の場所にあります。それでも問題が解決しない場合は、質問を編集してthe smallest-possible, yet complete and stand-alone example that reproduces the problem(MCVE)と記載してください。さておき、あなたの `NSDecimalNumber`が心配されたの宣言の` retain`修飾子のないよう


@interface MyObject: NSObject <NSCoding> 
@property (nonatomic, retain) NSDecimalNumber *miles; // use `strong` if using ARC 
@end 

@implementation MyObject 

- (instancetype)initWithCoder:(NSCoder *)coder { 
    self = [super init]; 
    if (self) { 
     self.miles = [coder decodeObjectForKey:@"miles"]; 
    } 
    return self; 
} 

- (void)encodeWithCoder:(NSCoder *)coder { 
    [coder encodeObject:_miles forKey:@"miles"]; 
} 

- (NSString *)description { 
    return [NSString stringWithFormat:@"<MyObject %p; miles=%@>", self, self.miles]; 
} 

// if ARC, remove this `dealloc` method 

- (void)dealloc { 
    [_miles release]; 

    [super dealloc]; 
} 

@end 

そして

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSURL *fileURL = [[[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:nil] URLByAppendingPathComponent:@"test.plist"]; 

    MyObject *object = [[MyObject alloc] init]; 
    object.miles = [NSDecimalNumber decimalNumberWithMantissa:42 exponent:0 isNegative:false]; 

    BOOL success = [NSKeyedArchiver archiveRootObject:object toFile:fileURL.path]; 
    NSLog(@"%@", success ? @"success" : @"failure"); 

    MyObject *object2 = [NSKeyedUnarchiver unarchiveObjectWithFile:fileURL.path]; 
    NSLog(@"%@", object2); 

    [object release]; // not needed if using ARC 
} 

@end 
関連する問題