NSCoding:保存自定义对象并加载到表视图iOS
我试图了解应用程序以保存数据。我有一个自定义对象NSCoding:保存自定义对象并加载到表视图iOS,ios,iphone,objective-c,cocoa-touch,Ios,Iphone,Objective C,Cocoa Touch,我试图了解应用程序以保存数据。我有一个自定义对象 @interface CellObject : NSObject <NSCoding> @property (nonatomic, strong) NSString *links; @property (nonatomic, strong) NSString *title; @property (assign) BOOL isFavorite; @end #import "CellObject.h" @implementa
@interface CellObject : NSObject <NSCoding>
@property (nonatomic, strong) NSString *links;
@property (nonatomic, strong) NSString *title;
@property (assign) BOOL isFavorite;
@end
#import "CellObject.h"
@implementation CellObject
@synthesize title, links;
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:title forKey:@"title"];
[aCoder encodeObject:links forKey:@"links"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self){
[self setTitle:[aDecoder decodeObjectForKey:@"title"]];
[self setLinks:[aDecoder decodeObjectForKey:@"links"]];
}
return self;
}
在Internet上查找教程,但它们不是很有帮助,请告诉我如何操作。如果对象在重新启动应用程序后仍然存在,它们将保留在单元格中?在您的视图中加载:
- (void)viewDidLoad
{
// ...
if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) { // Check if the file exist.
NSMutableData* data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]]; // Retrieve the data from the file
self.rssObjectArray = [[NSKeyedUnarchiver unarchiveObjectWithData:data] mutableCopy];
}
}
还有你的
- (NSString *)dataFilePath
{
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"CustomFeed.plist"];
/*BOOL result = [NSKeyedArchiver archiveRootObject:self.rssObjectArray toFile:path];
// This line above erase the file when it's called, remove all the code i commented.
if(result == YES)
{
NSLog(@"Array saved");
}*/
return path;
}
通过这些修改,我测试了您的应用程序及其工作情况。我做了测试,但它仍然不工作,也许我做错了什么我编辑了问题:((void)application willresignative:(NSNotification*)notification{CellObject*cellObj=[[CellObject alloc]init];//这里是存档的空对象,您应该在这里对要存档的对象进行编码。)不起作用(((这是我的项目,如果你能帮忙,我会非常感激。你能把项目发给我吗?因为我已经完成了上面描述的工作,但没有任何改变。显然我遗漏了一些东西。我的邮件cfyz2301@gmail.com。谢谢。我已向您发送了响应,但您还应在每次修改rssObjectArray对象时尝试保存数据。
- (NSString *)dataFilePath
{
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"CustomFeed.plist"];
/*BOOL result = [NSKeyedArchiver archiveRootObject:self.rssObjectArray toFile:path];
// This line above erase the file when it's called, remove all the code i commented.
if(result == YES)
{
NSLog(@"Array saved");
}*/
return path;
}