Use of <time.h> in Objective-C code
ID |
objectivec.maintainability.avoid_time_h |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Api Misuse |
Language |
Objective-C |
Description
Reports an include of <time.h> or a call to its clock, conversion and formatting functions from Objective-C code.
Rationale
The C time API is unspecified in exactly the places an application depends on. The epoch, the resolution and the encoding of time_t and clock_t are all implementation-defined, and asctime, ctime, gmtime and localtime return a pointer into a single shared static buffer, so two calls from different threads - or even two calls in one expression - overwrite each other. None of it is calendar-aware: it has no notion of the user’s locale, of a time-zone database update, or of the twenty-four-hour setting, so dates formatted this way are wrong for part of the audience.
The following code illustrates the pattern detected by this rule:
// FLAGGED: Use of <time.h> in Objective-C code
#include <time.h>
#import <Foundation/Foundation.h>
Remediation
Use the Foundation date types, which are thread safe, locale and calendar aware, and follow the user’s settings - NSDate and NSTimeInterval for instants and durations, NSCalendar/NSDateComponents for calendar arithmetic, and NSDateFormatter (or NSISO8601DateFormatter for machine-readable output) for formatting and parsing. For monotonic elapsed time use [[NSProcessInfo processInfo] systemUptime] or mach_absolute_time.