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

  • 备忘录模式
    设计存储中心,指定存储接口,实现存储机制。
    • 优化存储方案
      统一存储规范,实现灵活多变的存储机制。

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

  • 应用,使用场景
    存储UIView的状态,
    数据库回退

备忘录中心

//
//  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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容