1

我是 iOS 编程新手,并且编写了一个简单的提醒样式应用程序,我现在正在重写它以正确实现 MVC 模型,因为以前我的所有代码都在视图控制器中。

我有一个名为 Event 的自定义类,具有属性名称、时间、重复等,然后是以下结构:

模型类

检索、处理和保存数据NSUserDefaults

根视图控制器

创建模型对象的一个​​实例并要求模型返回所有​​事件对象,NSUserDefaults然后将它们显示在UITableView

编辑事件视图控制器

[editEventVC initWithEvent:theEvent];

通过 init 方法传递在表格单元格中选择的特定事件对象并显示所有可编辑的属性

EditEventPropertyViewController

[editEventPropertyVC initWithValue:propertyValue];

通过 init 方法传递要编辑的属性值(例如事件名称),并通过委托方法返回用户更新的值

这是实现此应用程序的正确方法吗?

NSUserDefaults完成 EditEventViewController 后,通过模型保存更新的 Event 对象的最佳方法是什么?通过代表?目前,我正在 rootViewController 中的 viewWillAppear 上重新加载 uitableview 数据,因此它必须在再次检索之前保存更新的数据。

谢谢

4

1 回答 1

1

You can store the collection of Event in NSUserDefaults. Since its a custom class, you need to implement NSCoding protocol for serialization to NSUserDefaults.

//Event.h

    @interface Event : NSObject<NSCoding>

    @property (nonatomic, copy)   NSString *name;
    @property (nonatomic, strong) NSDate *time;
    @property (nonatomic) NSInteger repeat;

    - (void)save;
    + (NSArray *)allEvents;

//Event.m
#define kSavedEvents @"SavedEvents"

#pragma mark - Encoding
- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.name  forKey:@"EventName"];
    [encoder encodeObject:self.time forKey:@"EventTime"];
    [encoder encodeObject:@(self.repeat) forKey:@"EventRepeat"];

}

#pragma mark - Decoding
- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];
    if (self)
    {
        _name   = [decoder decodeObjectForKey:@"EventName"];
        _time   = [decoder decodeObjectForKey:@"EventTime"];
        _repeat = [[decoder decodeObjectForKey:@"EventRepeat"]integerValue];

    }
    return self;
}

You need to archive the data while storing to NSUserDefaults and unarchive when fetching

 (void)save
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSData *savedData = [defaults objectForKey:kSavedEvents];


    NSMutableArray *savedEvents = [@[] mutableCopy];

    //Some events are already there in there
    if (savedData) {
        savedEvents = [[NSKeyedUnarchiver unarchiveObjectWithData:savedData]mutableCopy];
    }

    [savedEvents addObject:self];

    //Archiving the savedEvents to data
    NSData *newEventData = [NSKeyedArchiver archivedDataWithRootObject:savedEvents];

    [defaults setObject:newEventData forKey:kSavedEvents];
    [defaults synchronize];
}

+ (NSArray *)allEvents
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *data = [defaults objectForKey:kSavedEvents];
    if (data)
    {
        return [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    return nil;
}

Hope this will get you started.

于 2013-03-06T09:02:13.780 回答