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?
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.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 astatic
would have to be initialized on start-up. If persistingWebServiceURL
andUserId
across different runs is desirable, thenNSUserDefaults
is a good approach; otherwise, astatic
is good enough.