BrettStuart
BrettStuart

Reputation: 325

NSKeyedArchiver archivedDataWithRootObject: does not call encodeWithCoder

I cant get the archivedDataWithRootObject method to call encodeWithCoder, it seems pretty simple from what I understand but it doesn't work. Here's the code:

#import <Foundation/Foundation.h>

@interface Details : NSObject <NSCoding>{

NSMutableArray *myArray;
}

@property(nonatomic,retain) NSMutableArray *myArray;

@end

#import "Details.h"

@implementation Details
@synthesize myArray;


-(id)init{
 [super init];
 return self;
}

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

NSLog(@"initWithCoder");
if (self = [super init])
{
    self.myArray = [[aDecoder decodeObjectForKey:@"details"]retain];

} 
return self;
}

- (NSMutableArray*)getDetails{

NSLog(@"getDetials");
// NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *details = [[NSUserDefaults standardUserDefaults] objectForKey:@"details"];
if (details != nil){ 
  NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:details];
    if (oldSavedArray != nil)
        self.myArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
    else
        self.myArray = [[NSMutableArray alloc] initWithCapacity:1];
 }
 return self.myArray;
}

- (void) addDetails:(NSMutableArray *)details{

      NSLog(@"add Details");

     [self.myArray addObject:details]; 
     [NSKeyedArchiver archivedDataWithRootObject:self.myArray];
  }

- (void) encodeWithCoder:(NSCoder *)coder;
{
  NSLog(@"encodeWithCoder");
  [coder encodeObject:self.myArray forKey:@"details"];
} 

@end

NSLog(@"encodeWithCoder") doesn't run. I might be missing something, If anyone has any ideas it would be appreciated.

Upvotes: 1

Views: 5052

Answers (1)

jackslash
jackslash

Reputation: 8570

[NSKeyedArchiver archivedDataWithRootObject:self.myArray];

You are telling the NSKeyedArchiver to archive the myArray variable, not the object you have just implemented <NSCoding> with!

Also that method returns NSData * which you then have to write to disk separately if needed.

Try this:

NSData * archivedData = [NSKeyedArchiver archivedDataWithRootObject:self];

Upvotes: 1

Related Questions