You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何同一NSDate对象经NSLog输出不同字符串?(Xcode 9.3)

Why Your NSDate Outputs Differ and How NSLog Works with %@

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 format YYYY-MM-DD HH:MM:SS ±HHMM. That’s why you see 1970-01-01 00:00:00 +0000.

  • Second call (NSLog(@"%@", date);): You expected this to call description, but it’s producing a localized, human-readable string (Thu Jan 1 01:00:00 1970). Here’s why: In modern toolchains, NSDate’s debugDescription method returns a string formatted for readability—using your device’s current time zone and locale. While standard %@ specifiers should call description, the Xcode debugger’s console (and rare edge cases in older SDKs) may default to debugDescription for NSDate objects. It’s also possible you accidentally used the debugger’s po (print object) command instead of NSLog, which explicitly uses debugDescription.

2. Underlying Mechanism of NSLog(@"%@", date)

When you use %@ in NSLog, the standard workflow is:

  1. NSLog parses the format string and recognizes %@ as the specifier for an object.
  2. It sends the description message to the provided object to generate a string representation.
  3. 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 use debugDescription if you’re using debugger tools or have legacy SDK behavior, resulting in a localized, human-friendly string.
  • The standard %@ behavior for NSLog is to call description, but debugging tools and older OS versions can introduce exceptions.

内容的提问来源于stack exchange,提问作者Jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:04:40