好的,我还在习惯Objective-c的工作方式。
让我们假设我正在制作一个待办事项列表应用。有些人说你应该创建一个类,而不是仅仅从plist中读取并将其加载到表中,我们可以将其称为ToDo
,其中包含例如:
NSString *title;
NSString *description;
好的,好的。现在我如何使用这样的类从plist或其他东西加载我的数据?我不明白创建一个小课程有何帮助。任何人都可以向我解释这是如何工作的吗?
答案 0 :(得分:0)
使用NSCoding协议创建NSObject的子类(如果要将其保存在plist中)
示例:* .h文件
@interface ToDo : NSObject <NSCoding> {
NSString *title;
NSString *toDoDescription;
}
@property (copy) NSString *title;
@property (copy) NSString *toDoDescription;
@end
示例:* .m文件
@implementation ToDo
@synthesize title, toDoDescription;
- (id)init
{
if ((self = [super init])) {
[self setTitle:@"none"];
[self setToDoDescription:@"none"];
}
return self;
}
- (void)dealloc
{
[title release];
[toDoDescription release];
[super dealloc];
}
// Next two methods and coding protocol are needed to save your custom object into plist
- (id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super init])) {
title = [[aDecoder decodeObjectForKey:@"title"] copy];
toDoDescription = [[aDecoder decodeObjectForKey:@"toDoDescription"] copy];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:title forKey:@"title"];
[aCoder encodeObject:toDoDescription forKey:@"toDoDescription"];
}
@end
使用NSKeyedArchiver将您的对象转换为NSData。然后将其添加到plist中。