我从自定义类中保存时遇到问题。我试图在 NSUserDefaults 的代码中的某个位置保存错误,但它不起作用。
H 文件:
#import <Foundation/Foundation.h>
@interface Errors : NSObject<NSCoding>
@property (nonatomic,strong) NSString* type;
@property (nonatomic,strong) NSString* verNum;
@property (nonatomic,strong) NSString* title;
@property (nonatomic,strong) NSString* content;
@property (nonatomic,strong) NSString* source;
@property (nonatomic,strong) NSString* userId;
@property (nonatomic,strong) NSNumber* videoId;
@end
M 文件:
#import "Errors.h"
@implementation Errors
@synthesize verNum;
@synthesize type;
@synthesize title;
@synthesize content;
@synthesize source;
@synthesize userId;
@synthesize videoId;
- (void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject:self.verNum forKey:@"verNum"];
[encoder encodeObject:self.type forKey:@"type"];
[encoder encodeObject:self.title forKey:@"title"];
[encoder encodeObject:self.content forKey:@"content"];
[encoder encodeObject:self.source forKey:@"source"];
[encoder encodeObject:self.userId forKey:@"userId"];
[encoder encodeObject:self.videoId forKey:@"videoId"];
}
- (id)initWithCoder:(NSCoder *)decoder{
self = [super init];
if( self != nil ) {
self.verNum = [decoder decodeObjectForKey:@"verNum"];
self.type = [decoder decodeObjectForKey:@"type"];
self.title = [decoder decodeObjectForKey:@"title"];
self.content = [decoder decodeObjectForKey:@"content"];
self.source = [decoder decodeObjectForKey:@"source"];
self.userId = [decoder decodeObjectForKey:@"userId"];
self.videoId = [decoder decodeObjectForKey:@"videoId"];
}
return self;
}
@end
保存:
errorsDitalis = [[Errors alloc]init];
errorsDitalis.verNum = (NSString *) [[request userInfo] objectForKey:@"verNum"];
errorsDitalis.type =(NSString *) [[request userInfo] objectForKey:@"type"];
errorsDitalis.title =(NSString *) [[request userInfo] objectForKey:@"title"];
errorsDitalis.content =(NSString *) [[request userInfo] objectForKey:@"content"];
errorsDitalis.source =(NSString *) [[request userInfo] objectForKey:@"source"];
errorsDitalis.userId =(NSString *) [[request userInfo] objectForKey:@"userId"];
errorsDitalis.videoId =(NSNumber *) [[request userInfo] objectForKey:@"videoId"];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:errorsDitalis forKey:@"ErrorList"];
[userDefaults synchronize];
加载:
Errors * newError = [[Errors alloc]init];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
newError = [userDefaults objectForKey:@"ErrorList"];
它只是为 newErrors 返回 nil。我尝试使用此帮助,但没有奏效。有人有想法吗?