我无法获得archivedDataWithRootObject方法来调用encodeWithCoder,从我的理解看起来很简单,但它不起作用。 这是代码:
#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”)无法运行。 我可能会遗漏一些东西,如果有人有任何想法,我们将不胜感激。
答案 0 :(得分:1)
[NSKeyedArchiver archivedDataWithRootObject:self.myArray];
您告诉NSKeyedArchiver
归档myArray
变量,而不是您刚刚实施的<NSCoding>
对象!
此方法还会返回NSData *
,然后您需要在需要时单独写入磁盘。
试试这个:
NSData * archivedData = [NSKeyedArchiver archivedDataWithRootObject:self];