开发者

How to create a class for a type of object?

开发者 https://www.devze.com 2023-03-12 09:49 出处:网络
Ok, I\'m still getting used to how Objective-c works. Lets suppose I\'m making a todo list app.Instead of just reading from a plist and loading it into a table, some people say that开发者_如何学Go y

Ok, I'm still getting used to how Objective-c works.

Lets suppose I'm making a todo list app. Instead of just reading from a plist and loading it into a table, some people say that开发者_如何学Go you should create a class, lets call it ToDo that contains for example:

NSString *title;
NSString *description;

Ok, fine. Now how would I use such a class to load my data from a plist or something? I don't understand how creating a little class helps. Can anyone explain to me how this works?


Just creat a subclass of NSObject with NSCoding protocol(if you want to save it in a plist)

Example: *.h file

@interface ToDo : NSObject <NSCoding> {

    NSString            *title;
    NSString            *toDoDescription;

}
@property (copy) NSString           *title;
@property (copy) NSString           *toDoDescription;

@end

Example: *.m file

@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

Use NSKeyedArchiver to covert your object into NSData. And then add it to a plist.

0

精彩评论

暂无评论...
验证码 换一张
取 消