首页 > 代码库 > 封装NSMapTable并简易的使用
封装NSMapTable并简易的使用
封装NSMapTable并简易的使用
NSMapTable是弱引用的字典,可以用来存储对象,该对象消失了也没有关系,对于控制器越级跳转相当有用:)
WeakDictionary.h 与 WeakDictionary.m
//// WeakDictionary.h// 弱引用字典//// http://www.cnblogs.com/YouXianMing/// Copyright (c) 2014年 Y.X. All rights reserved.//#import <Foundation/Foundation.h>#define GET_WEAK_OBJECT(key) [WeakDictionary objectForKey:(key)]#define REGISTER_WEAK_OBJECT(object, key) [WeakDictionary addObject:(object) forKey:(key)]@interface WeakDictionary : NSObject+ (void)addObject:(id)object forKey:(NSString *)key;+ (id)objectForKey:(NSString *)key;@end
//// WeakDictionary.m// 弱引用字典//// http://www.cnblogs.com/YouXianMing/// Copyright (c) 2014年 Y.X. All rights reserved.//#import "WeakDictionary.h"static NSMapTable *weakDictionary = nil;@implementation WeakDictionary+ (void)initialize{ if (self == [WeakDictionary class]) { // 强引用key值弱引用object weakDictionary = [NSMapTable strongToWeakObjectsMapTable]; }}+ (void)addObject:(id)object forKey:(NSString *)key{ if (object == nil || key == nil) { NSLog(@"object or key should not be nil."); return; } if ([weakDictionary objectForKey:key] == nil) { [weakDictionary setObject:object forKey:key]; }}+ (id)objectForKey:(NSString *)key{ return [weakDictionary objectForKey:key];}@end
提供的两个category
NSObject+WeakDictionary.h 与 NSObject+WeakDictionary.m
//// NSObject+WeakDictionary.h// YouXianMing//// Created by YouXianMing on 14-9-20.// Copyright (c) 2014年 YouXianMing. All rights reserved.//#import <Foundation/Foundation.h>@interface NSObject (WeakDictionary)- (void)storeToWeakDictionaryWithKey:(NSString *)key;@end
//// NSObject+WeakDictionary.m// YouXianMing//// Created by YouXianMing on 14-9-20.// Copyright (c) 2014年 YouXianMing. All rights reserved.//#import "NSObject+WeakDictionary.h"#import "WeakDictionary.h"@implementation NSObject (WeakDictionary)- (void)storeToWeakDictionaryWithKey:(NSString *)key{ [WeakDictionary addObject:self forKey:key];}@end
NSString+WeakDictionary.h 与 NSString+WeakDictionary.m
//// NSString+WeakDictionary.h// YouXianMing//// Created by YouXianMing on 14-9-20.// Copyright (c) 2014年 YouXianMing. All rights reserved.//#import <Foundation/Foundation.h>@interface NSString (WeakDictionary)- (id)recoverFromWeakDictionary;@end
//// NSString+WeakDictionary.m// YouXianMing//// Created by YouXianMing on 14-9-20.// Copyright (c) 2014年 YouXianMing. All rights reserved.//#import "NSString+WeakDictionary.h"#import "WeakDictionary.h"@implementation NSString (WeakDictionary)- (id)recoverFromWeakDictionary{ return [WeakDictionary objectForKey:self];}@end
使用示例的话,以上一篇教程为例子来演示: http://www.cnblogs.com/YouXianMing/p/3983530.html
封装NSMapTable并简易的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。