有关此代码的引用计数的问题 [英] Question about reference count of this code

查看:148
本文介绍了有关此代码的引用计数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,参数的引用计数为3(由NSLog显示)...我想理解为什么...我试图管理这里的内存,并遇到一些根本的误解...似乎每次对象在代码中被引用时,引用计数上升,但是,在这种情况下,引用只引用一次(除了分配),因此将导致我相信引用计数应该只是2.无论如何...有人可以向我解释为什么参数的retainCount为3?

  NSString * authToken = [[NSDictionary dictionaryWithContentsOfFile:[GetFilePath pathForFile]] objectForKey:@auth_token]; 
NSString * apiSig = [MD5Gen returnMD5Hash:[NSString stringWithFormat:@xxxxxxx%@,authToken]];
NSString * arguments = [[NSString alloc] initWithFormat:@xxxxxxxx%@%@,authToken,apiSig];
NSString * encodedArguments = [arguments stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL * url = [[NSURL alloc] initWithString:encodedArguments];
NSLog(@%i,[arguments retainCount]);


解决方案



不要使用-retainCount。



对象的绝对保留计数没有意义。



您应该调用 release 与保持对象的次数完全相同。



查看内存管理指南






在此特定情况下,保留计数可能会受到 stringByAddingPercentEscapesUsingEncoding: 的内部实现细节。



除了聪明的好奇心,它真的没有关系。如果你保留一个对象,你应该释放它。


In the code below, arguments has a reference count of 3 (shown by NSLog)...i would like to understand why...I am trying to manage the memory here and am running into some fundamental misunderstandings...it seems like every time the object is reference in the code the reference count goes up, however, in this case, arguments is only referenced once (other than the allocation), and would therefore lead me to believe that the reference count should only be 2. At any rate...can someone please explain to me why arguments has a retainCount of 3?

NSString *authToken = [[NSDictionary dictionaryWithContentsOfFile:[GetFilePath pathForFile]] objectForKey: @"auth_token"];
NSString *apiSig = [MD5Gen returnMD5Hash:[NSString stringWithFormat:@"xxxxxxx%@", authToken]];
NSString *arguments = [[NSString alloc] initWithFormat:@"xxxxxxxx%@%@", authToken, apiSig];
NSString *encodedArguments = [arguments stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [[NSURL alloc] initWithString: encodedArguments];
NSLog(@"%i", [arguments retainCount]);

解决方案

(Since Dave asked for it)

Do not use -retainCount.

The absolute retain count of an object is meaningless.

You should call release exactly same number of times that you caused the object to be retained. No less (unless you like leaks) and, certainly, no more (unless you like crashes).

See the Memory Management Guidelines for full details.


In this specific case, the retain count might be being bumped by stringByAddingPercentEscapesUsingEncoding: as in internal implementation detail.

Beyond an intellectual curiosity, it really doesn't matter. If you retain an object, you should release it.

这篇关于有关此代码的引用计数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆