Is it safe to assume static variables never get cleared?

483 views Asked by At

I've had users reporting random crashes within an application, particularly when switching between other apps. Unfortunately for the time being, I am unable to replicate the crash or get hold of the crash logs. Within my iOS application, I have a static class where I store variable which I refer to throughout the app - I have a hunch that this is what is causing the issue:

namespace DemoApp.BusinessLogic
{
    public static class AppController
    {
        public static string WebServiceURL { get; set; }
        public static int UserId { get; set; }
        public static User User { get; set; }
        //...
    }
}  

The values for these are initiated when the user first logs into the app. My understanding was that static references are never cleared by ARC, is this correct? Am I safe to assume that these values never be cleared until the application is closed?

I could replace these static values to references to NSUserDefaults:

namespace DemoApp.BusinessLogic
{
    public static class AppController
    {
        public static string WebServiceURL { 
            get { 
                return NSUserDefaults.StandardUserDefaults.StringForKey("WebServiceURL"); 
            } 
            set { 
                NSUserDefaults.StandardUserDefaults.SetString(value, "WebServiceURL"); 
            }
        }

        public static string UserId { 
            get { 
                return NSUserDefaults.StandardUserDefaults.StringForKey("UserId"); 
            } 
            set { 
                NSUserDefaults.StandardUserDefaults.SetString(value, "UserId"); 
            }
        }

        //...
    }
}  

Is this a better way of doing things?

1

There are 1 answers

2
Sergey Kalinichenko On BEST ANSWER

My understanding was that static references are never cleared by ARC, is this correct?

Yes, this is correct. ARC will not clear your static variables, unless they are weak and the object that they reference has no other references.

I could replace these static values to references to NSUserDefaults. Is this a better way of doing things?

This comparison is not an apples-to-apples, because the value in NSUserDefaults will survive closing the application and even powering down the device, while a static would have to be initialized on start-up. If persisting WebServiceURL and UserId across different runs is desirable, then NSUserDefaults is a good approach; otherwise, a static is good enough.