In my app I would like to find out the exact time of any crash from previous session, reported via Crashlytics. I'm setting up Crashlytics this way:
- (void) setUpCrashlytics
{
[[Fabric sharedSDK] setDebug:YES];
[CrashlyticsKit setDebugMode:YES];
[CrashlyticsKit setDelegate:self];
[Fabric with:#[[Crashlytics class]]];
}
I'm simulating an app crash by pressing a button, few minutes after app launches:
[CrashlyticsKit crash];
I tried to get the last session crash time using CrashlyticsDelegate:
#pragma mark - CrashlyticsDelegate Methods
- (void) crashlyticsDidDetectReportForLastExecution:(CLSReport *) report completionHandler:(void (^)(BOOL)) completionHandler
{
BOOL isCrash = report.isCrash; //this is TRUE
NSDate *crashDate = report.crashedOnDate;
NSDate *reportCreation = report.dateCreated;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
completionHandler(YES);
}];
}
But unfortunately, both dates are displaying not the crash time, but last session launch time. Any ideas? Thanks.
Matt here from Crashlytics.
Unfortunately, you've found a bug :( I've taken note of it, and I'll make sure it gets looked at.
I am also interested to know what how you intend to use this information. It's just a use-case I haven't heard of before.
Also, keep in mind that particular delegate callback is problematic. As we indicate in the header documentation, that method's API requires us to sacrifice some reliability features. I'd recommend avoiding it, because our ability to successfully report crashes is much better without it. Yes, we do have plans to add a new read-only API that avoids this tradeoff. For now, I would only recommend it if you have a very pressing need that cannot be satisfied any other way.
Also, since it was brought up in the comments - this API will never be invoked for an out-of-memory termination. Those are technically not crashes, and are not are not reported as such. The mechanisms we use are completely different, and outlined in our documentation here: https://docs.fabric.io/apple/crashlytics/OOMs.html. We use a heuristic, and is not (nor claims to be) 100% reliable. It's pretty good though.
Hope this is helpful - and hit up our support forums/email for further help. Stack overflow is harder to monitor :)
Update:
I thought it would be useful more info here, now that I understand what Radu is trying to achieve. The upshot is using this delegate method cannot achieve what he'd like, and in fact will only make the situation worse.
At the moment Crashlytics is initialized (during the -[Fabric with:] call), the SDK prepares and enqueues any crashes on disk to NSURLSession's background uploading facility. We do this because we want make sure our upload process is not interrupted by another crash. To my knowledge, this is a feature unique to our implementation, we've been using it for years, and it works amazingly well. Crashlytics is basically immune to reporting failures caused by crashes on subsequent launches.
Now, in order to make sure this works as well as possible, we have to do this work synchronously during launch. So, if you start Crashlytics/Fabric on a background thread, or do background work concurrently with the SDK being initialized, it compromises our ability to reliably complete this process before another potential crash could occur.
But, there's another issue. If the delegate is set, and has this method implemented, we must respect the API's contract and ask the delegate if it is ok for us to enqueue the report before we send it. For better or worse, this API also does not do this synchronously. So, when you implement this delegate method, you are opening a large window of time where:
Crashlytics will not send reports because it is waiting for your permission to do so
another crash can cause a loss of pending reports
During the time between the delegate being invoked and the callback being called, you aren't giving more time for reports to be sent. You're just adding delay before the SDK knows that you've given permission for us to send them.
(Personally, I find this API very problematic, and would like to remove it. But, we need to keep it for backwards compatibility. It's really my fault for not implementing a new API that doesn't allow the delegate to cancel the report. Such an API wouldn't be subject to a delay in enqueue the report and could avoid all these problems. One day, we'll have that and we can finally deprecate this one.)
So, to improve early-launch crash handling, I'd recommend the following:
never initialize Crashlytics on a background thread
make sure to initialize Crashlytics as early in launch as you can, ideally the very first thing your application does
never use this delegate method
The only exceptions should really be:
you are attempting to implement a user-facing crash report permissions dialog (it was designed for exactly this use case)
want to blow away sensitive cache data that may be responsible crashes
have some other analytics mechanism and you want to count crashes
I'd also recommend, again, contacting our support. Missing crashes are common. Missing crashes caused by SDK issues are uncommon, are monitored, and we have a ton of SDK-side and backend-side code to understand and minimize them.
Related
Description
I would like to catch all exceptions that are occurring in iOS app and log them to file and eventually send them to back-end server used by the app.
I've been reading about this topic and found usage of signals sent by device and handling them, but I'm not sure if it's gonna break App Store Review guidelines or it may introduce additional issues.
I've added following to AppDelegate:
NSSetUncaughtExceptionHandler { (exception) in
log.error(exception)
}
signal(SIGABRT) { s in
log.error(Thread.callStackSymbols.prettified())
exit(s)
}
signal(SIGILL) { s in
log.error(Thread.callStackSymbols.prettified())
exit(s)
}
signal(SIGSEGV) { s in
log.error(Thread.callStackSymbols.prettified())
exit(s)
}
Questions
Is this good approach, any other way?
Will it break App Store Review guidelines because of usage of exit()
Is it better to use kill(getpid(), SIGKILL) instead of exit()?
Resources
https://github.com/zixun/CrashEye/blob/master/CrashEye/Classes/CrashEye.swift
https://www.plcrashreporter.org/
https://chaosinmotion.blog/2009/12/02/a-useful-little-chunk-of-iphone-code/
former Crashlytics iOS SDK maintainer here.
The code you've written above does have a number of technical issues.
The first is there are actually very few functions that are defined as safe to invoke inside a signal handler. man sigaction lists them. The code you've written is not signal-safe and will deadlock from time to time. It all will depend on what the crashed thread is doing at the time.
The second is you are attempting to just exit the program after your handler. You have to keep in mind that signals/exception handlers are process-wide resources, and you might not be the only one using them. You have to save pre-existing handlers and then restore them after handling. Otherwise, you can negatively affect other systems the app might be using. As you've currently written this, even Apple's own crash reporter will not be invoked. But, perhaps you want this behavior.
Third, you aren't capturing all threads stacks. This is critical information for a crash report, but adds a lot of complexity.
Fourth, signals actually aren't the lowest level error system. Not to be confused with run time exceptions (ie NSException) mach exceptions are the underlying mechanism used to implement signals on iOS. They are a much more robust system, but are also far more complex. Signals have a bunch of pitfalls and limitations that mach exceptions get around.
These are just the issues that come to me off the top of my head. Crash reporting is tricky business. But, I don't want you to think it's magic, of course it's not. You can build a system that works.
One thing I do want to point out, is that crash reporters give you no feedback on failure. So, you might build something that works 25% of the time, and because you are only seeing valid reports, you think "hey, this works great!". Crashlytics had to put in effort over many years to identify the causes of failure and try to mitigate them. If this is all interesting to you, you can check out a talk I did about the Crashlytics system.
Update:
So, what would happen if you ship this code? Well, sometimes you'll get useful reports. Sometimes, your crash handling code will itself crash, which will cause an infinite loop. Sometimes your code will deadlock, and effectively hang your app.
Apple has made exit public API (for better or worse), so you are absolutely within the rules to use it.
I would recommend continuing down this road for learning purposes only. If you have a real app that you care about, I think it would be more responsible to integrate an existing open-source reporting system and point it to a backend server that you control. No 3rd parties, but also no need to worry about doing more harm than good.
Conclusion
It is possible to create custom crash reporter but it is definitely not recommended because there is a lot going on in background that could be easily forgotten and can introduce a lot of undefined behaviors. Even usage of third party frameworks can be troublesome but it is generally better way to go.
Thanks to everyone for providing information regarding this topic.
Answers to questions
Is this good approach, any other way?
Approach I mentioned in original question will have influence on Apple's own crash reporter and it introduces undefined behavior because of bad handling of signals. UNIX signals are not covering every error and API handling work with async signal safe functions. Mach exception handling which is used by Apple's crash reporter is better option but it is more complex.
Will usage of exit() break Apple App Store review?
No. Usage of exit() is more related to the normal operation of app. If app is crashing anyway, calling exit() isn't problem.
Is it better to use kill(getpid(), SIGKILL) instead of exit()?
Quote from Eskimo:
You must not call exit. There’s two problems with doing that:
exit is not async signal safe. In fact, exit can run arbitrary code
via handlers registered with atexit. If you want to exit the process,
call _exit.
Exiting the process is a bad idea anyway, because it will either
prevent the Apple crash reporter from running or cause it to log
incorrect state (the state of your signal handler rather than the
state of the crashed thread).
A better solution is to unregister your signal handler (set it to
SIG_DFL) and then return
Additional details (full context)
Since I cross posted this questions to Apple's official support forum and got really long and descriptive answer from well known Eskimo I would like to share it with anyone who decides to go same path as I did and starts researching this approach.
Quote from Eskimo
Before we start I’d like you to take look at my shiny new Implementing
Your Own Crash Reporter post. I’ve been meaning to write this up for
a while, and your question has give me a good excuse to allocate the
time.
You wrote:
I've got a requirement to catch all exceptions that are occuring in
iOS app and log them to file and eventually send them to back-end
server used by the app.
I strongly recommend against doing this. My Implementing Your Own
Crash Reporter post explains why this is so hard. It also has some
suggestions for how to avoid problems, but ultimately there’s no way
to implement a third-party crash reporter that’s reliable, binary
compatible, and sufficient to debug complex problems
With that out of the way, let’s look at your specific questions:
Is this good approach at all?
No. The issue is that your minimalist crash reporter will disrupt the
behaviour of the Apple crash reporter. The above-mentioned post
discusses this problem in gory detail.
Will it break App Store Review guidelines because of usage of exit()?
No. iOS’s prohibition against calling exit is all about the normal
operation of your app. If your app is crashing anyway, calling exit
isn’t a problem.
However, calling exit will exacerbate the problem I covered in the
previous point.
Is it better to use kill(getpid(), SIGKILL) instead?
That won’t improve things substantially.
callStackSymbols are not symbolicated, is there a way to symbolicate
callStackSymbols?
No. On-device symbolication is extremely tricky and should be
avoided. Again, I go into this in detail in the post referenced
above.
Share and Enjoy
Since links can break I will also quote post.
Implementing Your Own Crash Reporter
I often get questions about third-party crash reporting. These
usually show up in one of two contexts:
Folks are trying to implement their own crash reporter.
Folks have implemented their own crash reporter and are trying to debug a problem based on the report it generated.
This is a complex issue and this post is my attempt to untangle some
of that complexity.
If you have a follow-up question about anything I've raised here,
please start a new thread in .
IMPORTANT All of the following is my own direct experience. None of it should be considered official DTS policy. If you have questions
that need an official answer (perhaps you’re trying to convince your
boss that implementing your own crash reporter is a very bad idea :-),
you should open a DTS tech support
incident and we can
discuss things there.
Share and Enjoy — Quinn “The Eskimo!” Apple Developer Relations,
Developer Technical Support, Core OS/Hardware let myEmail = "eskimo"
+ "1" + "#apple.com"
Scope
First, I can only speak to the technical side of this issue. There
are other aspects that are beyond my remit:
I don’t work for App Review, and only they can give definitive answers about what will or won’t be allowed on the store.
Doing your own crash reporter has significant privacy implications.
IMPORTANT If you implement your own crash reporter, discuss the privacy impact with a lawyer.
This post assumes that you are implementing your own crash reporter.
A lot of folks use a crash reporter from another third party. From my
perspective these are the same thing. If you use a custom crash
reporter, you are responsible for its behaviour, both good and bad,
regardless of where the actual code came from.
Note If you use a crash reporter from another third party, run the tests outlined in Preserve the Apple Crash Report to verify that
it’s working well.
General Advice
I strongly advise against implementing your own crash reporter. It’s very easy to implement a basic crash reporter that works well
enough to debug simple problems. It’s impossible to create a good
crash reporter, one that’s reliable, binary compatible, and sufficient
to debug complex problems.
“Impossible?”, I hear you ask, “That’s a very strong word for Quinn to
use. He’s usually a lot more circumspect.” And yes, that’s true, I
usually am more circumspect, but in this case I’m extremely
confident of this conclusion.
There are two fundamental problems with implementing your own crash
reporter:
On iOS (and the other iOS-based platforms, watchOS and tvOS) your crash reporter must run inside the crashed process. That means it can
never be 100% reliable. If the process is crashing then, by
definition, it’s in an undefined state. Attempting to do real work in
that state is just asking for problems 1.
To get good results your crash reporter must be intimately tied to system implementation details. These can change from release to
release, which invalidates the assumptions made by your crash
reporter. This isn’t a problem for the Apple crash reporter because
it ships with the system. However, a crash reporter that’s built in
to your product is always going to be brittle.
I’m speaking from hard-won experience here. I worked for DTS during
the PowerPC-to-Intel transition, and saw a lot of folks with custom
crash reporters struggle through that process.
Still, this post exists because lots of folks ignore my general
advice, so the subsequent sections contain advice about specific
technical issues.
WARNING Do not interpret any of the following as encouragement to implement your own crash reporter. I strongly advise against that.
However, if you ignore my advice then you should at least try to
minimise the risk, which is what the rest of this document is about.
1 On macOS it’s possible for your crash reporter to run out of
process, just like the Apple crash reporter. However, that presents
its own problems: When running out of process you can’t access various
bits of critical state for the crashed process without being tightly
bound to implementation details that are not considered API.
Preserve the Apple Crash Report
You must ensure that your crash reporter doesn’t disrupt the Apple
crash reporter. Some fraction of your crashes will not be caused by
your code but by problems in framework code, and a poorly written
crash reporter will disrupt the Apple crash reporter and make it
harder to diagnose those issues.
Additionally, when dealing with really hard-to-debug problems, you
really need the more obscure info that’s shown in the Apple crash
report. If you disrupt that info, you end up making the hard problems
harder.
To avoid these issues I recommend that you test your crash reporter’s
impact on the Apple crash reporter. The basic idea is:
Create a program that generates a set of specific crashes.
Run through each crash.
Verify that your crash reporter produces sensible results.
Verify that the Apple crash reporter also produces sensible results.
With regards step 1, your test suite should include:
An un-handled language exception thrown by your code
An un-handled language exception thrown by the OS (accessing an NSArray out of bounds is an easy way to get this)
A memory access exception
An illegal instruction exception
A breakpoint exception
Make sure to test all of these cases on both the main thread and a
secondary thread.
With regards step 4, check that the resulting Apple crash report
includes correct values for:
The exception info
The crashed thread
That thread’s state
Any application-specific info, and especially the last exception backtrace
Signals
Many third-party crash reporters use UNIX signals to catch the crash.
This is a shame because using Mach exception handling, the mechanism
used by the Apple crash reporter, is generally a better option.
However, there are two reasons to favour UNIX signals over Mach
exception handling:
On iOS-based platforms your crash reporter must run in-process, and doing in-process Mach exception handling is not feasible.
Folks are a lot more familiar with UNIX signals. Mach exception handling, and Mach messaging in general, is pretty darned obscure.
If you use UNIX signals for your crash reporter, be aware that this
API has some gaping pitfalls. First and foremost, your signal handler
can only use async signal safe functions 1. You can find a list
of these functions in the sigaction man
page
2.
WARNING This list does not include malloc. This means that a crash reporter’s signal handler cannot use Objective-C or Swift, as
there’s no way to constrain how those language runtimes allocate
memory. That means you’re stuck with C or C++, but even there you
have to be careful to comply with this constraint.
The Operative: It’s worse than you know.
Many crash reports use functions like backtrace (see its man
page)
to get a backtrace from their signal handler. There’s two problems
with this:
backtrace is not an async signal safe function.
backtrace uses a naïve algorithm that doesn’t deal well with cross signal handler stack frames [3].
The latter example is particularly worrying, because it hides the
identity of the stack frame that triggered the signal.
If you’re going to backtrace out of a signal, you must use the crashed
thread’s state (accessible via the handlers uapparameter) to start
your backtrace.
Apropos that, if your crash reporter wants to log the state of the
crashed thread, that’s the place to get it.
Finally, there’s the question of how to exit from your signal handler.
You must not call exit. There’s two problems with doing that:
exit is not async signal safe. In fact, exit can run arbitrary code via handlers registered with atexit. If you want to exit the
process, call _exit.
Exiting the process is a bad idea anyway, because it will either prevent the Apple crash reporter from running or cause it to log
incorrect state (the state of your signal handler rather than the
state of the crashed thread).
A better solution is to unregister your signal handler (set it to
SIG_DFL) and then return. This will cause the crashed process to
continue execution, crash again, and generate a crash report via the
Apple crash reporter.
1 While the common signals caught by a crash reporter are not
technically async signals (except SIGABRT), you still have to treat
them as async signals because they can occur on any thread at any
time.
2 It’s reasonable to extend this list to other routines that are
implemented as thin shims on a system call. For example, I have no
qualms about calling vm_read (see below) from a signal handler.
[3] Cross signal handler stack frames are pushed on to the stack by
the kernel when it runs a signal handler on a thread. As there’s no
API to learn about the structure of these frames, there’s no way to
backtrace across one of these frames in isolation. I’m happy to go
into details but it’s really not relevant to this discussion. If
you’re interested, start a new thread in and we can chat there.
Reading Memory
A signal handler must be very careful about the memory it touches,
because the contents of that memory might have been corrupted by the
crash that triggered the signal. My general rule here is that the
signal handler can safely access:
Its code
Its stack
Its arguments
Immutable global state
In the last point, I’m using immutable to mean immutable after
startup. I think it’s reasonable to set up some global state when
the process starts, before installing your signal handler, and then
rely on it in your signal handler.
Changing any global state after the signal handler is installed is
dangerous, and if you need to do that you must be careful to ensure
that your signal handler sees a consistent state, even though a crash
might occur halfway through your change.
Note that you can’t protect this global state with a mutex because
mutexes are not async signal safe (and even if they were you’d
deadlock if the mutex was held by the thread that crashed). You
should be able to use atomic operations for this, but atomic
operations are notoriously hard to use correctly (if I had a dollar
for every time I’ve pointed out to a developer they’re using atomic
operations incorrectly, I’d be very badly paid (-: but that’s still a
lot of developers!).
If your signal handler reads other memory, it must take care to avoid
crashing while doing that read. There’s no BSD-level API for this
1, so I recommend that you use vm_read.
1 The traditional UNIX approach for doing this is to install a
signal handler to catch any memory exceptions triggered by the read,
but now we’re talking signal handling within a signal handler and
that’s just silly.
Writing Files
If your want to write a crash report from your signal handler, you
must use low-level UNIX APIs (open, write, close) because only
those low-level APIs are documented to be async signal safe. You must
also set up the path in advance because the standard APIs for
determining where to write the file (NSFileManager, for example) are
not async signal safe.
Offline Symbolication
Do not attempt to do symbolication from your signal handler. Rather,
write enough information to your crash report to support offline
symbolication. Specifically:
The addresses to symbolicate
For each Mach-O image in the process:
The image path
The image UUID
The image load address
You can get most of the Mach-O image information using the APIs in
<mach-o/dyld.h> 1. Be aware, however, that these APIs are not
async signal safe. You’ll need to get this information in advance and
cache it for your signal handler to record.
This is complicated by the fact that the list of Mach-O images can
change as you process loads and unloads code. This requires you to
share mutable state with your signal handler, which is exactly what I
recommend against in Reading Memory.
Note You can learn about images loading and unloading using _dyld_register_func_for_add_image
and_dyld_register_func_for_remove_image respectively.
1 I believe you’ll need to parse the Mach-O load commands to get the
image UUID.
I have been debugging an app for a while and am ready to upload it to app store. However, I still get occasional crashes that are hard to duplicate or debug--for example when pushing buttons in weird sequences. If I write these sequences down, I can debug but inevitably it happens when I haven't written it down and these can be difficult to replicate.
I know I need to just call it a day and leave future bug fixes for next release. I have removed all the abort() statements I had in testing. However, occasionally rather than getting a crash that lets you just close the app and reopen, I get one that makes it impossible to open the app without reinstalling. For example, this just happened, with a
'NSGenericException', reason: '*** Collection <__NSCFSet: 0x174a41b90> was mutated while being enumerated.'
This resulted from switching VCs during a background sync to the cloud.
I can live with crashes where you just need to reopen but not with ones that render the app unusable. Are there any guidelines for types of crashes to help you focus on the really fatal ones?
Or is there anything you can do to keep crashes from bricking app?
You should just fix this problem. Since you have this crashlog with that error message, you know which method can raise the problem, so you've got a good head start on fixing it, even if the problem manifests itself inconsistently and/or in a variety of ways.
But the occasional crash may not seem like too much of an inconvenience to you, but it is the quickest way to 1-star reviews and unhappy customers. I suspect you will quickly regret distributing an app with known, easily reproduced crashes.
But, a few observations:
It sounds like your background update process is mutating your model objects used by the main thread.
If possible, I'd suggest being careful to simply do not change any of your model objects in the background thread, but rather populate a local variable and when you're ready to update the UI accordingly, dispatch both the model update and UI refresh to the main thread.
If you cannot do this for some reason, you have to synchronize all interaction of model updates with some mechanism such as locks, GCD serial queue, reader-writer model, etc. This is slightly more complicated approach, but can be done.
I would advise temporarily editing your target's "scheme" and turn on the thread sanitizer:
It may possibly help you identify and more easily reproduce these sorts of problems. And the more easily you can reproduce the problem, the more easily you will be able to fix the issue.
You say:
Or is there anything you can do to keep crashes from bricking app?
It sounds like the "save" operation is somehow leaving the results in persistent storage in an internally inconsistent manner. Any one of the following would help, though I'd suggest you do all three if possible):
At the risk of repeating myself, fix the crash (it's always better to eliminate the source of the problem than try to program around manifestations of the problem);
Depending upon how you're saving your results, you may be able to employ an atomic save operation, so that if it fails half way, it won't leave it in an inconsistent state; we can't advise how you should do that without seeing code snippet illustrating how you're saving the results, but it's often an option;
Make sure that, if the "load" process that reads the persistent storage can fail, that it does so gracefully, rather than crashing; see if you can get it in this state where the app is failing during start-up, and then carefully debug what's going on in the start-up process that is causing the app to fail with this particular set of data in persistent storage. In the "devices" section, there is an option to download the data associated with an app, so you can carefully diagnose what's going on.
So I've had a look at the apple documentation on the NSUserDefaults's synchronize() method. See below for reference:
https://developer.apple.com/reference/foundation/userdefaults/1414005-synchronize
The page currently reads:
Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.
However, what I still don't understand is when should this method be called? For example, should it be called every time the user changes the app's settings? Or should I just trust that the background api is going to handle that? And does the leaving of the view immediately after a settings change in memory result in that change being lost?
Also, when might a failure to call synchronize() result in user settings not getting changed correctly?
Furthermore, what is the cost (performance, memory or otherwise) of calling this method? I know it involves reading and writing from/to the disk but does that really take that much effort on phones?
There seems to be so much confusion about user defaults. Think of it this way. It's essentially the same as you having a global dictionary available throughout your app. If you add/edit/remove a key/value to the global dictionary, that change is immediately visible anywhere in your code. Since this dictionary is in memory, all would be lost when your app terminates if it wasn't persisted to a file. NSUserDefaults automatically persists the dictionary to a file every once in a while.
The only reason there is a synchronize method is so your app can tell NSUserDefaults to persist the dictionary "now" instead of waiting for the automatic saving that will eventually happen.
And the only reason you ever need to do that is because your app might be terminated (or crash) before the next automatic save.
In my own apps, the only place I call synchronize is in the applicationDidEnterBackground delegate method. This is to ensure the latest unsaved changes are persisted in case the app is terminated while in the background.
I think much of the confusion comes from debugging an app during development. It's not uncommon during development that you kill the app with the "stop" button in the debugger. And many times this happens before the most recent NSUserDefaults changes have been persisted. So I've developed the habit of putting my app in the background by pressing the Home button before killing the app in the debugger whenever I want to make sure the latest updates are persisted.
Given the above summary, let's review your questions:
should it be called every time the user changes the app's settings?
No. As described above, any change is automatically available immediately.
Or should I just trust that the background api is going to handle that?
Yes, trust the automatic persistence with the exception of calling synchronize when your app enters the background.
And does the leaving of the view immediately after a settings change in memory result in that change being lost?
This has no effect. Once you add/edit/delete a key/value in NSUserDefaults, the change is made.
Also, when might a failure to call synchronize() result in user settings not getting changed correctly?
The only time a change can be lost is if your app is terminated before the latest changes have been persisted. Calling synchronize when your app enters the background solves most of these issues. The only remaining possible problem is if your app crashes. Any unsaved changes that have not yet been persisted will be lost. Fix your app so it doesn't crash.
Furthermore, what is the cost (performance, memory or otherwise) of calling this method? I know it involves reading and writing from/to the disk but does that really take that much effort on phones?
The automatic persistence is done in the background and it simply writes a dictionary to a plist file. It's very fast unless you are not following recommendations. It will be slower if you are misusing NSUserDefaults to store large amounts of data.
Apple's documentation for synchronize() has been updated and now reads:
Waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used.
UPDATE
As anticipated, it has been deprecated as mentioned in Apple Doc
synchronize()
Waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used.
Original Answer
-synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release.
-synchronize blocks the calling thread until all in-progress set operations have completed. This is no longer necessary. Replacements for previous uses of -synchronize depend on what the intent of calling synchronize was. If you synchronized…
— …before reading in order to fetch updated values: remove the synchronize call
— …after writing in order to notify another program to read: the other program can use KVO to observe the default without needing to notify
— …before exiting in a non-app (command line tool, agent, or daemon) process: call CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
— …for any other reason: remove the synchronize call
As far i know, synchronize is used to sync the data immediately but iOS can handle that in smart way. So you dont need to call it everytime. If you call it everytime then it will turn to performance issue.
Check apple documentation:
Official Link
Please, anyone, help me: Is calling NSUserDefaults's synchronize() method mandatory?. If I don't call it, what will happen? My application is working fine without it.
No.
Since iOS12, it isn't mandatory anymore.
Apple says:
This method is unnecessary and shouldn't be used.
You can find more information on iOS12 release note:
UserDefaults
NSUserDefaults has several bug fixes and improvements:
Removed synchronization requirements. It's no longer necessary to use synchronize, CFPreferencesAppSynchronize, or CFPreferencesSynchronize. These methods will be deprecated in a future version of the OS.
Now that you don't need to call these synchronization methods, the performance characteristics of NSUserDefaults and Preferences Utilities are slightly different: The time taken for enqueueing write operations is now paid by the writing thread, rather than by the next thread to call synchronize or do a read operation.
From the docs:
Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.
Meaning that if you kill the app right after something is written to the defaults without the periodic interval catching it, it will get lost. You probably did not kill the app right after a write event yet which is why your app seems to work fine so far.
Normally it works perfectly fine and you only have to use it in special cases, for example when the app will close directly after writing to NSUserDefaults. So you can simply add the synchronize method to the corresponding AppDelegate-method.
As others have said, you don't normally have to call synchronize at all.
Normally the system calls it for you so your defaults changes get written.
However, when working with Xcode it's pretty common to terminate your app by pressing command period or clicking the stop button. In that case it terminates the app without warning and your user defaults changes will quite likely not be written out, and will be lost.
This can be a good thing or a bad thing, depending on what you want. It's certainly confusing.
You can "fix" it by calling synchronize each time you make a change, or on some time interval. However that does slow your app down and increase it's power requirements (both by very small amounts.) If you are in a loop, writing changes to 10,000 server or Core Data records, and you change user defaults after each pass, then calling synchronize after each one might have a measurable effect on app speed and on battery life. In most cases you're not likely to notice the difference however.
This question io3->ios4 upgrade said to support applicationWillResignActive. While implementing this call, I also implemented applicationDidEnterBackground and applicationWillEnterForeground. However, I found that my app would crash. After some debugging on the simulator I determined that I needed to reinitialize a key data structure in applicationWillEnterForeground. So my question is how would I have known that from reading the documentation? (In fact, I may be doing the wrong thing and just so happened to get it working again.) Is there an exact description of what to do when these methods are called?
Thanks.
The only things you should do when supporting multitasking, is saving the state of your app when it enters the background, and reload it when it becomes active. (If you generate a new template in Xcode, you'll see this.)
Saving state means writing any user preferences or data to disk. Reloading the state involves reading saved preferences and data, recreating any in memory data structures that might need it (like in your example you gave).
In most circumstances, there's little else you need to do. The only thing that would crash your app that is unique to multitasking would be trying to run code in the background for longer than the allotted amount of time, (which is 10 minutes.) Otherwise, it sounds like you have got other problems with your code.