objective-c - 关于iOS中引用计数的问题
PHPz
PHPz 2017-04-17 17:53:18
0
1
243

我不是很明白其中“nsmutablearray类对象被赋值给变量obj,但obj自己并不持有该对象,使用retain可以持有该对象”这句话。

然后我在网上看到这个,应该是对应“非自己生成的对象,自己也能持有”这个情况,然后我写了下面的代码

NSMutableArray *array = [NSMutableArray arrayWithObjects: @"one", @"two", nil];  
NSString *elem = array[0];   
[array removeAllObjects];   
NSLog(@"%@", elem);

既然removeallobjects了就应该被dealloc了,为什么还能打印出elem呢?

还有第二种代码,person被release之后为什么还可以访问name

People *person = [[People alloc] init];
[person release];
NSString *name = person.name;
NSLog(@"%@", name);
PHPz
PHPz

学习是最好的投资!

reply all(1)
巴扎黑

This is a problem with the reference counting mechanism. Simply put, when an object is initialized through alloc, copy, etc., its retainCount will become 1. Every time it is retained, retainCount increases by 1, and every time it is released, retainCount decreases by 1. , when an object is added to a collection (such as array), it will be automatically retained once, and when it is removed from the collection, it will be automatically released. When the object's retainCount becomes 0, the object will be marked as free. In principle, the object should no longer be accessed at this time, because it may be released at any time.

"Objects that are not generated by yourself can also be held by yourself" means that although an object is not generated by yourself, you can retain it, so that its retainCount is increased by 1. If there is no excessive release elsewhere, it will be released after you release it. Before it, its retainCount was at least 1, which is the same as if you were holding it.

Your last two problems are that your test code uses the wrong object. NSString does not follow the retain/release method. You can replace all NSString in your test with NSMutableString or any object ObjectA and give it a try.

The last question is that retainCount should be 0 after person is released. Why can I still access person.name? The reason is that the object pointed to by the person pointer will not be cleared immediately after its retainCount reaches 0. It may need to wait until the next runloop. At this time, the person pointer still points to that object, and name is an NSString, so it can be accessed.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template