Chap12. bronze challenge


#1

It was not sure whether to put saveChanges in DrawView or Controller, and whether to call it from DidEnterBackground or viewDidDisappear, though ended up with the former.

BNRLine.h
  @interface BNRLine : NSObject <NSCoding>

BNRLine.m
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeCGPoint:self.begin forKey:@"begin"];
    [aCoder encodeCGPoint:self.end forKey:@"end"];
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        _begin = [aDecoder decodeCGPointForKey:@"begin"];
        _end = [aDecoder decodeCGPointForKey:@"end"];
    }
    return self;
}

BNRDrawView.h
-(BOOL)saveChanges;

BNRDrawView.m
-(NSString *)lineArchivePath
{
    NSArray *documentDirectories =
        NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                            NSUserDomainMask,
                                            YES);
    NSString *documentDirectory = [documentDirectories firstObject];
    return [documentDirectory stringByAppendingPathComponent:@"lines.archive"];
}

-(BOOL)saveChanges
{
    NSString *path = [self lineArchivePath];
    return [NSKeyedArchiver archiveRootObject:self.finishedLines
                                       toFile:path];
}

-(instancetype)initWithFrame:(CGRect)r
{
    self = [super initWithFrame:r];

    if (self) {
        NSString *path = [self lineArchivePath];
        _finishedLines = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        if (!_finishedLines) {
            _finishedLines = [[NSMutableArray alloc] init];
        }

BNRAppDelegate.c
  #import "BNRDrawView.h"

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    BNRDrawView *view = (BNRDrawView *)self.window.rootViewController.view;
    BOOL success = [view saveChanges];
    if (success) {
        NSLog(@"Saved all of the BNRLines");
    } else {
        NSLog(@"Could not save any of the BNRLines");
    }
}