iOS 备忘录模式(简单使用)

2017-03-08  本文已影响408人  印林泉

FastCoder 本地序列化,转NSData,比对象实现NSCopying存储好

备忘录中心

//
//  MementoCenter.h
//  LearnMemento
//
//  Created by 印林泉 on 2017/3/8.
//  Copyright © 2017年 ylq. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "MementoCenterProtocol.h"

@interface MementoCenter : NSObject

/**
 存储备忘录对象

 @param object 值
 @param key 键
 */
+ (void)saveMementoObject:(id<MementoCenterProtocol>)object withKey:(NSString *)key;

/**
 获取备忘录对象

 @param key 键
 @return 值
 */
+ (id)mementoObjectWithKey:(NSString *)key;

@end
//
//  MementoCenter.m
//  LearnMemento
//
//  Created by 印林泉 on 2017/3/8.
//  Copyright © 2017年 ylq. All rights reserved.
//

#import "MementoCenter.h"

@implementation MementoCenter

+ (void)saveMementoObject:(id)object withKey:(NSString *)key {
    
}

+ (id)mementoObjectWithKey:(NSString *)key {
    return nil;
}

@end

备忘录中心协议,存储的对象必须满足这个协议,才能存储到备忘录中心

//
//  MementoCenterProtocol.h
//  LearnMemento
//
//  Created by 印林泉 on 2017/3/8.
//  Copyright © 2017年 ylq. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol MementoCenterProtocol <NSObject>

/**
 获取状态

 @return 状态值
 */
- (id)currentState;

/**
 从某种状态恢复

 @param state 状态值
 */
- (void)recoverFromState:(id)state;

@end

存储对象(苹果)

//
//  Apple.h
//  LearnMemento
//
//  Created by 印林泉 on 2017/3/8.
//  Copyright © 2017年 ylq. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "MementoCenterProtocol.h"

@interface Apple : NSObject<MementoCenterProtocol>

@end
//
//  Apple.m
//  LearnMemento
//
//  Created by 印林泉 on 2017/3/8.
//  Copyright © 2017年 ylq. All rights reserved.
//

#import "Apple.h"

@implementation Apple

- (id)currentState {
    return self;
}

- (void)recoverFromState:(id)state {
    
}

@end

使用

//
//  ViewController.m
//  LearnMemento
//
//  Created by 印林泉 on 2017/3/8.
//  Copyright © 2017年 ylq. All rights reserved.
//

#import "ViewController.h"
#import "Apple.h"
#import "MementoCenter.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    Apple *apple = [[Apple alloc] init];
    ///save
    [MementoCenter saveMementoObject:[apple currentState] withKey:@"Apple"];
    ///get
    [apple recoverFromState:[MementoCenter mementoObjectWithKey:@"Apple"]];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
上一篇下一篇

猜你喜欢

热点阅读