BNRImageStore对象将负责保存用户所拍的所有照片。创建一个名为BNRImageStore的NSObject子类,然后在BNRImageStore.h中添加以下代码:
#import <Foundation/Foundation.h>
@interface BNRImageStore : NSObject
+ (instancetype)sharedStore;
- (void)setImage:(UIImage *)image forKey:(NSString *)key;
-(UIImage *)imageForKey:(NSString *)key;
- (void)deleteImageForKey:(NSString *)key;
@end
接下来在BNRImageStore.m的类扩展中声明一个属性,用于存储照片。
@interface BNRImageStore ()
@property (nonatomic, strong) NSMutableDictionary *dictionary;
@end
@implementation BNRImageStore
和BNRItemStore类似,BNRImageStore也是单例。在BNRImageStore.m中加入以下代码,确保BNRImageStore的单例状态。
@implementation BNRImageStore
+ (instancetype)sharedStore
{
static BNRImageStore *sharedStore = nil;
if (!sharedStore) {
sharedStore = [[self alloc] initPrivate];
}
return sharedStore;
}
// 不允许直接调用init方法
- (instancetype)init
{
@throw [NSException exceptionWithName:@“Singleton”
reason:@“Use +[BNRImageStore sharedStore]”
userInfo:nil];
return nil;
}
// 私有初始化方法
- (instancetype)initPrivate
{
self = [super init];
if (self) {
_dictionary = [[NSMutableDictionary alloc] init];
}
return self;
}
然后实现其他三个新方法,代码如下:
- (void)setImage:(UIImage *)image forKey:(NSString *)key
{
[self.dictionary setObject:image forKey:key];
}
- (UIImage *)imageForKey:(NSString *)key
{
return [self.dictionary objectForKey:key];
}
- (void)deleteImageForKey:(NSString *)key
{
if (!key) {
return;
}
[self.dictionary removeObjectForKey:key];
}