English 中文(简体)
为什么你制造临时物体,将其归入变数,然后予以释放?
原标题:why do you make temporary objects, set them to variables, then release them?

我常常看到这样的情况:

NSArray *tmpArr = [[NSArray alloc] initWithObjects:@"Info", nil];
self.userInfo = tmpArr;
[tmpArr release];

而不是:

self.userInfo = [[NSArray alloc] initWithObjects:@"Info", nil];

是否有任何人知道为什么最高级的法典样本更为普及? 它对记忆的管理是否比后者更正确?

最佳回答

第二部法典由于没有释放阵列,造成记忆泄露。 在大多数情况下,物体类型的特性(如NSArray 在这种情况下)要么是retain,要么是copy ,要么是增加分配值的参照数,要么是复制整个物体。 然后,如果不再需要,当地变量可以(而且应当)释放。

将使用<代码>autorelease:

self.userInfo = [[[NSArray alloc] initWithObjects:@"Info", nil] autorelease];

或简单:

self.userInfo = [NSArray arrayWithObjects:@"Info", nil];
问题回答

假设财产<代码>用户信息为标注<代码>retain,第二种形式将泄露记忆。 <代码>[[NSArray alloc] initWithObjects]将形成一个阵列,编号为一。 将其转让给<代码>retain<> /code> 财产将增加对二者的提及,从来不会再回落到零,并且将予以释放。 可以通过使用所列出的首份表格或:

self.userInfo = [[[NSArray alloc] initWithObjects:@"Info", nil] autorelease];

因此,汽车释放将减少在下游乐团的交接点上点数。 从那时起,用户信息数据库被清除,参考数字将降至零,阵列将销毁。

You should also take a look at this question

Apart from any other reasons there might be, it makes the code more readable and helps to prevent errors.

你的两个例子并不相同,因为你想在第二个例子中公布新版的<代码>>。 你们需要

self.userInfo = [[[NSArray alloc] initWithObjects:@"Info", nil] autorelease];

页: 1

QED first reason ;-P

此外,当你首先制造一个地方变量时,你就可以在通过财产公布这些物体之前建造更复杂的物体。 例如,如果你在此使用可互换<>>>阵列,并用一些更为复杂的逻辑加以填充,将其分配到物权之外,而且只有在填满时,贵阶层的客户才能获得财产,其内容只能是半成品——这是一条关于零星和硬性复制泡沫的巨大规定。

因此,即便在您的情形下,也不必使用当地变量(如果您有<代码>autorelease/code>)。 d 我们使用新的自动参考资料“ARC”,自动解决泄漏问题,我认为,first获取所有材料和then使其可见一斑。

清洁法典规则:





相关问题
List Contents of Directory in a UITableView

I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code: - (...

iPhone NSUserDefaults persistance difficulty

In my app i have a bunch of data i store in the NSUserdefaults. This information consists of an NSObject (Object1) with NSStrings and NSNumbers and also 2 instances of yet another object (Object2). ...

Writing a masked image to disk as a PNG file

Basically I m downloading images off of a webserver and then caching them to the disk, but before I do so I want to mask them. I m using the masking code everyone seems to point at which can be found ...

Resize UIImage with aspect ratio?

I m using this code to resize an image on the iPhone: CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:...

Allowing interaction with a UIView under another UIView

Is there a simple way of allowing interaction with a button in a UIView that lies under another UIView - where there are no actual objects from the top UIView on top of the button? For instance, ...

热门标签