封装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
时间: 2024-12-21 01:22:50