创建BNRImageStore

作者: 乂iang | 来源:发表于2019-02-20 00:52 被阅读0次

    11.3 创建BNRImageStore

    摘自《iOS编程》

    目的:

    创建这个类是为了打开的item中如果有图片,在点开这个的时候才去把照片从磁盘读取到内存中。

    思路与步骤:

    1. 新建文件,为NSObject子类。

    2. 添加: sharedStore 单例。
      setImage 设置照片,参数是一个image一个key。
      imageForKey 为UIImage类型。
      deleteImageForKey 用于删除。

    补充:1. 单例是什么?

    1. instancetype 是什么? instancetype 返回的是方法,id返回的是指向任意对象的指针。
    1. 在.m文件中,声明一个属性用于存储照片,NSMutableDictionary。

    补充:NSMutableDictionary

    1. 确保BNRImageStore的单例状态。其中调用到initPrivate,其内容为super init 及 初始化dictionary。
    shareStore = [[self alloc]initPrivate];
    /// 加上
    _dictionary = [[NSMutableDictionary alloc]init];
    
    1. 实现其他几个方法,即相对应的dictionary的方法:setObject、objectForKey、removeObjectForKey方法。

    思维导图:

    BNRImageStore.png

    遇到的问题:

    1. 没办法用UIImage
      方法:引入头文件。参考此链接:https://stackoverflow.com/questions/26412635/ios-8-expected-a-type
    #import <UIKit/UIKit.h>
    

    源码【持续修改中】

    BNRImageStore.h

    #import <Foundation/Foundation.h>
    @interface BNRImageStore:NSObject
    +(instancetype) sharedStore;
    -(void) setImage:(UIImage *)image forKey:(NSString *)key;
    -(UIImage *)imageForKey:(NSString *)key;
    -(void) deleteIamgeForKey:(NSString *)key;
    @end
    

    BNRImageStore.m

    #import "BNRImageStore.h"
    #import <UIKit/UIKit.h>
    
    @interface BNRImageStore()
    
    @property (nonatomic,strong) NSMutableDictionary * dictionary;
    @end
    
    @implementation BNRImageStore
    + (instancetype) shareStore{
        static BNRImageStore *shareStore = nil;
        if(!shareStore){
            shareStore = [[self alloc]initPrivate];
        }
        return shareStore;
    }
    
    - (instancetype)init{
        @throw [NSException exceptionWithName:@"Singleton" reason:@"User+[BNRImageStore shareStore]" userInfo:nil];
        return nil;
        
    }
    
    -(instancetype)initPrivate{
        self = [super init];
        if(self){
            _dictionary = [[NSMutableDictionary alloc]init];
        }
        return  self;
    }
    
    -(void) setImage:(id)image forKey:(NSString *)key{
        [self.dictionary setObject:image forKey:key];
    }
    
    -(UIImage *)imageForKey:(NSString *)key{
        return [self.dictionary objectForKey:key];
    }
    
    -(void) deleteIamgeForKey:(NSString *)key{
        if(!key){
            return;
        }
        [self.dictionary removeObjectForKey:key];
    }
    
    @end
    

    相关文章

      网友评论

        本文标题:创建BNRImageStore

        本文链接:https://www.haomeiwen.com/subject/youzeqtx.html