Design a singleton dictionary that does not strongly reference objects
As we all know, when using nsdictionary to store objects, it will strongly reference objects, resulting in the reference count of stored objects plus 1. Sometimes, we want to use a singleton to store objects, but you do not want to strongly reference the stored objects. How can this be achieved?
Here, we can use nsmaptable to implement this function.
I will provide the source code directly:
Weakdictionary. H + weakdictionary. m
/// Weakdictionary. h // weak reference dictionary // 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 // weak reference dictionary // 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]) {// weak reference object weakdictionary = [nsmaptable strongtoweakobjectsmaptable] ;}+ (void) addobject :( ID) object forkey :( nsstring *) key {If (Object = nil | key = nil) {nslog (@ "Object & Key shocould not be nil. "); return;} If ([weakdictionary objectforkey: Key] = nil) {[weakdictionary setobject: Object forkey: Key] ;}+ (ID) objectforkey :( nsstring *) key {return [weakdictionary objectforkey: Key] ;}@ end
Test code:
//// Appdelegate. M // weakdic /// copyright (c) 2014 y. x. all rights reserved. // # import "appdelegate. H "# import" weakdictionary. H "# import" yxgcd. H "# import" model. H "@ interface appdelegate () @ property (nonatomic, strong) Model * model; @ property (nonatomic, strong) gcdtimer * timer; @ end @ implementation appdelegate-(bool) application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) launchoptions {// create a temporary model * TMP = [model new]; // register the weak reference object register_weak_object (TMP, @ "model"); // hold this temporary model self through attributes. model = TMP; // after 7 s, this attribute holds another model (the original model was released) [[gcdqueue mainqueue] execute: ^ {self. model = [model new];} afterdelay: nsec_per_sec * 7]; // start the timer to monitor the temporary model _ timer = [[gcdtimer alloc] initinqueue: [gcdqueue mainqueue]; [_ timer event: ^ {nslog (@ "% @", get_weak_object (@ "model");} timeinterval: nsec_per_sec]; [_ timer start]; return yes ;} @ end
Test legend:
As for how to design such a Singleton, this kind of Singleton that can hold objects without increasing the object reference count, you can think about its usefulness :)