ARC下NSMutableDictionary 無法使用retainCount
今天用到 NSMutableDictionary 在alloc之後
很自然的就補了release
想要觀察有沒有放乾淨
所以使用了retainCount卻發生了錯誤
NSMutableDictionary* jsonObject = [[NSMutableDictionary alloc] init] ;
[jsonObject setObject:account forKey:@"username"];
[jsonObject setObject:password forKey:@"password"];
[jsonObject setObject:@"2" forKey:@"source"];
NSString *jsonInput = [jsonObject JSONRepresentation];
NSLog(@"jsonObject RetanCount:%@", [jsonObject retainCount]); //Bad_Access Here
爬了一下文,原來arc在建立NSMutableDictionary這類的物件時。便已經會自動使用autorelease 因此不支援retainCount
值得注意的是 當NSMutableDictionary裡面每增加一個物件(KEY)時
該NSMutableDictionary的retain便會自動加一 不過在新的arc功能下 已經不用那麼在意retain值了。順便memo一下NSDictionary與NSKeyedArchiver的用法
You shouldn't use -retainCount to figure out what is going on. The Apple docs specifically state:
Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.
Back to your question: When you add an object to an NSDictionary, the object is retained. When you remove the object from the dictionary (or dealloc the dictionary), it is released. That's all you need to know. So as long as the object is inside the dictionary, it will remain alive.
NSMutableDictionary *NSMDict = [[[NSMutableDictionary alloc]init]autorelease];
[NSMDict setObject:[NSString stringWithFormat:@"aaa"] forKey:@"Key1"];
[NSMDict setObject:[NSString stringWithFormat:@"bbb"] forKey:@"Key2"];
//使用NSKeyedArchiver
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"raw"];
[NSKeyedArchiver archiveRootObject:NSMDict toFile:path];
NSMutableDictionary *NSMDict2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"Key1 : %@\n",[NSMDict2 objectForKey:@"Key1"]);
NSLog(@"Key2 : %@\n",[NSMDict2 objectForKey:@"Key2"]);
See also :
留言