Objective-C weak reference zombie - ios

I'm trying to create a zombie object to detect sending messages to a deallocated object.
Say i have a strong property object A with a weak reference to object B. When B is deallocated my weak reference becomes nil but calling a method e.g [obj1.obj2 somemethod] simply returns nil not causing a crash.
Is there a way to test zombies using weak references? I can only crash using unsafe_unretained.

Is there a way to test zombies using weak references
(I take it that by "zombies" you actually mean dangling pointers...)
Not directly, no. The whole point of ARC-weak references is that they prevent dangling pointers. (As you rightly say, they safely replace the potential dangling pointer with nil — and there's no penalty for sending a message to nil.)
The reason there can be dangling pointer crashes in real life is that most of Cocoa does not use ARC. (As you rightly say, it uses unsafe_unretained.)

Related

Is it redundant in Swift to use weak and optional for the same variable?

I'm new in Swift and in the Apple docs I see:
Use a weak reference whenever it is valid for that reference to become >nil at some point during its lifetime.
Shouldn't I achieve that just by using "?" for optional types?
in other words:
Do the weak and ? overlap?
The compiler complains if I don't define a variable as optional when is weak, so I feel like I could just remove it and forget about it, but I feel I'm just misunderstanding it.
Thanks!
No, weak and optional are not the same, but there is some interplay between the two.
Optional just means that a variable can be nil, either by assigning nil yourself, or becoming nil through some other means.
The weak keyword has to do with memory management. When a variable is not weak (i.e. it is strong), it means that ARC holds a strong reference to the instance that is assigned. So even when there are no other references to it, the instance will stay alive in memory because the variable still "holds it".
When a a variable is weak, it does not hold a strong reference to it. That means that when there are no other strong references to it, the instance will be deallocated, and the variable will become nil automatically. This also explains why a weak variable must be optional.
The document that you linked to actually explains this quite clearly.
weak is related to memory management that ARC should remove that variable from memory or not. If your variable is weak then ARC would clear that memory to which it is pointing to as soon as all the strong references to that memory destroyed and when the memory is cleared then even the varaible is non-optional it will have nill because its memory is cleared.
But the optional has nothing to do with memory and it is directly related to the variable value that it can either contains the actual value or the nil.
Optional and non-optional properties differ in that optionals may be nil, while non-optional cannot.
weak and strong (property is strong by default without weak keyword) properties differ in that weak don't increase property's retain count, while strong do. If a weak property isn't strongly retained somewhere else, it will be deallocated. weak properties must also be optional.

Does ARC set its reference type instance properties to nil before deallocation?

This question occured to me while reading this.
My question is in reference to the image below:
Once john is set to nil, Person instance no longer has any more strong reference and hence will be deallocated. But Apartment has two strong references and one of which is by the property on Person instance that would be soon deallocated. I believe, this strong reference continue to remain after deallocation and goes out of reach by the code.
So, setting unit14A to nil will remove only one strong reference to Apartment instance and it should not be deallocated as there would be one more strong reference due to the above case.
But, as the document says Apartment instance promptly got deallocated. To me, this can only happen if at the time of Person instance deallocation it sets its apartment property to nil, by that removing that strong reference on Apartment instance. But I couldn't find any documentation to verify this.
So, How does the Apartment instance get deallocated? What happened to the strong reference from the Person instance apartment property?
Can someone help me to understand this?
Objective-C objects are reference counted, meaning that for each object, the system keeps track of how many other objects hold a reference to it. This is object's reference count. Two special messages, retain and release, are used to maintain the reference count behind the scene. Once reference count goes down to zero, the system deallocates the object.
ARC provides "magic" to make reference counting work in a declarative way. The compiler knows every strong reference in your code, so when you do this
myStrongRef = nil;
the compiler quietly inserts a call to release in front of the assignment:
[myStrongRef release];
myStrongRef = nil;
To me [deallocation of Apartment] can only happen if at the time of Person instance deallocation it sets its apartment property to nil, by that removing that strong reference on Apartment instance.
Setting a strong reference to nil one way of breaking a strong reference. It is sufficient, but it isn't necessary. The important thing about setting a strong reference to nil is not the act of setting itself, but what happens immediately before it: the instance referred to by the strong reference gets a release message, instructing it to decrement its reference count. That is precisely what ARC does behind the scene for you: it sends the release message to Apartment, without setting Person's reference to nil.
How does the Apartment instance get deallocated? What happened to the strong reference from the Person instance apartment property?
Once strong reference from Person has sent its release message to Apartment, that strong reference disappears. The actual pointer may be set to Apartment's address, but nobody cares about it, because the Person itself is unreachable.
The life of an object depends on it's reference count, not any actual pointer to the object.
Strong reference is a way of speaking, there is no difference between a strong and weak reference, they are just pointers. The difference is that when a strong reference is created the reference count of the object pointed to in incremented and when deleted the reference count is decreased. When an object's reference count would become zero the object is deallocated.
Your intuition is correct. When an object is being deallocated under ARC all the strong references it holds are first relinquished - essentially they are set to nil, but in practice the implementation may differ.
This is also what happens when a method returns, or a block of code containing declarations exits, all the strong references held in local variables are relinquished.
All the details can be found in the Clang documentation.
HTH
Obviously not before deallocation, but during deallocation.
When an object's reference count goes to zero, the deallocation process starts. The object is marked as "being deallocated". At that point, the object will die (unlike Java, where it can be recovered). If an object is marked like this, it cannot be assigned to weak references (they stay nil), or to strong references.
Then dealloc is called, that is the dealloc methods that you have written. After that, strong references are set to nil, reducing their reference counts, then associated objects are removed, and finally the memory for the object is deleted.

Are Unowned references set to 'nil' when deinitialized?

I'm confused on this topic in swift where it is said that unowned references must always have a value and cannot be optional, also meaning they cannot be set to 'nil'....well I just saw a program on the Apple documents for swift that instance 'A' with an unowned reference to instance 'B' was deinitialized and deallocated right after instance 'B' was deinitialized/deallocated......when a var is deinitialzed/dealloc doesn't it mean they are set to 'nil'??? Instance B is an optional so sure it can hold 'nil' but why did instance 'A' get deinitialized when its supposed to always have a value????
PS: If this helps..... instance 'B' was an optional type with a strong reference to instance 'A'
The point of an unowned reference is to hold a weak reference to something that you are guaranteeing (based on your application logic) will not be deallocated prior to the object that has the unowned reference. You can read more in the documentation.
In a sense it is a similar thing to an implicitly unwrapped optional type (such as String!). You're telling the compiler that you won't ever access the value when it is nil, and if you do your program will crash.
An object is deinitialized when its strong reference count drops to 0, but it is not deallocated until its weak reference count also drops to zero.
"Deinitializing" an object means that its deinit function is executed if it has one, releasing any resource that it holds, and clearing any references that it may have (potentially deinitializing and deallocating more objects). "Deallocating" is when the memory is reclaimed by the runtime. A deinitialized object's reference counting header is still valid.
When you access a weak reference, the Swift runtime ensures that the object is still in an initialized state. If it isn't, the weak reference is set to nil and the deinitialized object's weak reference count is decremented.
Unowned references also count towards the weak reference count. When you access an unowned reference, the Swift runtime also ensures that the object is in an initialized state; but if it is not, instead of clearing the reference (it can't do that because it is not optional), it crashes your program.
This effectively makes an unowned reference behave like an implicitly-unwrapped optional, whereas a weak reference behaves like an optional.
The tradeoff for self-zeroing weak references and clean-crashing unowned references is that an object's backing memory cannot be reclaimed until all of its weak references have been tested or deinitialized, and until all of its unowned references have been deinitialized.
Source: Swift runtime code
It is meaningless to talk about what an unowned variable "holds" after the object it points to has been deallocated, because Swift guarantees that your app will crash if you ever try to access the variable after the object it points to has been deallocated:
Note also that Swift guarantees your app will crash if you try to
access an unowned reference after the instance it references is
deallocated. You will never encounter unexpected behavior in this
situation. Your app will always crash reliably, although you should,
of course, prevent it from doing so.

assign in NON-ARC and retain cycle

How retain cycle was tackled in NON-ARC !
I know assign is an alternative to weak.
weak will have its value set to nil If object allocated is deallocated whereas assign is not
so how it was done earlier can anybody help me understand
Zeroing weak references (what ARC calls weak) only exist under ARC.
Non-zeroing weak references (what ARC calls unsafe_unretained) can be used in MRC or ARC, and is the only kind of "weak reference" that is used in MRC.
You are asking how to avoid dangling references with non-zeroing weak references. You just have to design the logic of the program so that it doesn't happen. It's not that hard.
Usually, a "parent" object will have strong references to "child" objects, and then a back-reference from the "child" object to the "parent" will be a weak reference (in this case a non-zeroing weak reference). All you have to do is, when the "parent" object is deallocated, in its deinitializer, nil out the back-references that the "child" objects have to it -- it can access these "child" objects since it has a reference to them.

Is it possible to implement NSFastEnumeration when using weak references?

I have a collection which maintains weak references to its objects. I'd like it to conform to NSFastEnumeration, but the buffer provided by countByEnumeratingWithState:objects:count: uses unsafe_unretained references. That creates a gap during which a returned reference could become invalid but not zeroed.
That's fine in the general case -- if the collection stuffs its (currently valid but weakly-referenced) object into the buffer and returns it, then the caller will presumably create its own strong reference if needed. But that leaves two problems:
(1) I don't see any guarantee that the for(){} iteration construct itself creates a temporary strong reference to the object, so if the contents of the {x} block changes something outside the collection in a way that causes the object to be released, then it'll have a dangling reference.
(2) There's still a small gap while returning from countByEnumeratingWithState: during which activity on another thread could invalidate the reference. My collection isn't meant to be thread-safe, but it would be nice if it could at least safely store references to objects which could be referenced on another thread, as there's really no way to prevent that in any multi-threaded application.
You can't return a strong reference directly to the caller. The caller won't release it, and the fast enumeration protocol does not guarantee that you will get a chance to release it yourself when the caller is done.
Instead you can retain+autorelease the objects before you store them into the buffer. That would guarantee the objects stay alive while the caller uses them. It may hurt the "fast" part of fast enumeration, but you would still get the "convenient syntax" part. If you add a nil check after you read the weak variable then you can avoid storing nil pointers into the buffer.

Resources