了解iOS中的内存管理 [英] Understanding memory management in ios

查看:39
本文介绍了了解iOS中的内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Objective-C,并对iPad应用程序进行编程.我一直不停地重新阅读一件事,那就是内存管理.我到那里...慢慢地.基本规则(例如,对于每个 alloc / retain 必须具有 release 的规则)很有用.但是,我还没有一件相对基本的事情,我想知道是否有人可以解释...

I am in the process of learnig objective-c and programming an iPad app. One thing I keep tripping myself up on and having to re-read is memory management. I am getting there...slowly. Basic rules such as for every alloc / retain you must have a release is useful. However, one relatively basic thing eludes me and I wonder if someone could explain...

采用以下代码...

NSArray *myArray = [[NSArray alloc] init];
myArray = [someNSSet allObjects];

这是相对简单的编码,需要 [myArray release] 语句.

This is relatively straight forward coding and would require a [myArray release] statement.

但是,我一直看到(实际上,我已经广泛使用了以下捷径" ...

However, I keep seeing examples of (and indeed, I have used extensively the following 'short cut'...

NSArray *myArray = (NSArray *)[someNSSet allObjects];

据我所知,当您使用(NSString *)时,您不需要使用 [myArray release] 语句,但是我不明白为什么.

How, as far as I understand when you use the (NSString *) you dont need to use a [myArray release] statement, but I dont understand why.

有人可以解释吗?

推荐答案

第一行:

NSArray *myArray = [[NSArray alloc] init] 

为数组分配了一些内存(实际上,在这种情况下,这是没有意义的,因为数组的大小为0.请记住,NSArray是不可变的!).变量myArray保留保留的内存区域的第一个字节的地址.

some amount of memory is allocated for an array (actually in this case it is senseless since the size of the array is 0. Keep in mind that NSArray is immutable!). The variable myArray holds the address of the first byte of the reserved memory area.

现在,在第二行中,更改myArray的值,该值现在将指向存储[someNSSet allObjects]的内存区域的第一个字节.现在,您不再知道在第一行中创建的数组存储在哪里.所以你有泄漏.

Now in the second line you change the value of myArray which now will point to the first byte of the memory area where [someNSSet allObjects] is stored. At this moment you do not know any more where the array is stored what you've created in the first line. And so you have a leak.

该行:

NSArray *myArray = (NSArray *)[someNSSet allObjects];

是正确的,因为此时您不保留任何内存.如果您不使用ARC,则可以调用keep来使GC远离引用的内存块.以其他方式,当对象的所有者释放它并尝试通过以下方式访问它时,您可能会收到BAD_EXEC:[myArray objectAtIndex:0]

is correct, since you do not reserve any memory at this point. If you are not using ARC you might call retain in order to keep GC away from the referenced block of memory. In other way you might receive a BAD_EXEC when the owner of the object releases it and you try to access it through e.g.: [myArray objectAtIndex:0]

这篇关于了解iOS中的内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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