为何同一NSDate对象经NSLog输出不同字符串?(Xcode 9.3)
Great question—let’s unpack this clearly and directly.
1. The Output Discrepancy Explained
Your two NSLog calls produce different results because they’re leveraging two distinct string representation methods of NSDate:
First call (
NSLog(@"%@", [date description]);): You’re explicitly invoking-[NSDate description]. In Xcode 9.3 (and SDKs targeting macOS 10.12+/iOS 10+), this method returns a UTC-based, machine-readable string in the formatYYYY-MM-DD HH:MM:SS ±HHMM. That’s why you see1970-01-01 00:00:00 +0000.Second call (
NSLog(@"%@", date);): You expected this to calldescription, but it’s producing a localized, human-readable string (Thu Jan 1 01:00:00 1970). Here’s why: In modern toolchains,NSDate’sdebugDescriptionmethod returns a string formatted for readability—using your device’s current time zone and locale. While standard%@specifiers should calldescription, the Xcode debugger’s console (and rare edge cases in older SDKs) may default todebugDescriptionforNSDateobjects. It’s also possible you accidentally used the debugger’spo(print object) command instead of NSLog, which explicitly usesdebugDescription.
2. Underlying Mechanism of NSLog(@"%@", date)
When you use %@ in NSLog, the standard workflow is:
- NSLog parses the format string and recognizes
%@as the specifier for an object. - It sends the
descriptionmessage to the provided object to generate a string representation. - That string is inserted into the format and printed to the console.
To confirm exactly which method is being called in your case, you can add a simple category to log invocations:
@interface NSDate (DebugLogging) @end @implementation NSDate (DebugLogging) - (NSString *)description { NSLog(@"description method called"); return [super description]; } - (NSString *)debugDescription { NSLog(@"debugDescription method called"); return [super debugDescription]; } @end
Running this with your code will show you whether NSLog is using description or debugDescription under the hood.
Summary
[date description]gives you a consistent, UTC-aligned string optimized for machines (modern SDKs).NSLog(@"%@", date)may usedebugDescriptionif you’re using debugger tools or have legacy SDK behavior, resulting in a localized, human-friendly string.- The standard
%@behavior for NSLog is to calldescription, but debugging tools and older OS versions can introduce exceptions.
内容的提问来源于stack exchange,提问作者Jack

