In objective-c, I know that a static variable (should?) retain its value for the lifetime of the program. But if it stores a pointer, does it count as strong in ARC? Can I depend on it and be assured that that instance will never go out of the heap once I assigned it to a static variable?
static ClassA* shared;
-(id)init
{
if (self=[super init]) {
shared=self;
}
return self;
}
A static pointer can be used to implement a function that always returns the same buffer to the program. This can be helpful in serial communication.
It is incorrect to use shared_ptr to manage static objects and there would be nothing to gain in doing so.
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects.
What is a Static Variable? In programming, a static variable is the one allocated “statically,” which means its lifetime is throughout the program run. It is declared with the 'static' keyword and persists its value across the function calls.
Yes you can rely on it, once it's assigned.
The Transitioning to ARC Release Notes state:
Under ARC, strong is the default for object types.
and then:
__strong is the default. An object remains “alive” as long as there is a strong pointer to it.
Given your static
pointer references the object, it will remain “alive”. The scope of a pointer (whether global, a pointer on the stack or an instance variable) makes no difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With