From e47c22480fe84c100019cd92d0296f0dd2a7f3f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Wed, 20 Apr 2022 20:27:16 +0200 Subject: [PATCH] Add QDebug operator for Objective-C id type Not every id is an NSObject, and even those that are are sometimes passed around as id, in which case we still want them to have pretty debug descriptions. Change-Id: I50a02cd8fb9d6a2cbde3c4aef81116033d10b72c Reviewed-by: Timur Pocheptsov Reviewed-by: Thiago Macieira --- src/corelib/io/qdebug.h | 2 ++ src/corelib/kernel/qcore_mac.mm | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/corelib/io/qdebug.h b/src/corelib/io/qdebug.h index 5d07a9f290f..847fc676ad2 100644 --- a/src/corelib/io/qdebug.h +++ b/src/corelib/io/qdebug.h @@ -530,6 +530,7 @@ inline QDebug operator<<(QDebug debug, QKeyCombination combination) QT_END_NAMESPACE Q_FORWARD_DECLARE_CF_TYPE(CFString); +typedef struct objc_object *id; Q_FORWARD_DECLARE_OBJC_CLASS(NSObject); QT_FOR_EACH_CORE_FOUNDATION_TYPE(QT_FORWARD_DECLARE_CF_TYPE) QT_FOR_EACH_MUTABLE_CORE_FOUNDATION_TYPE(QT_FORWARD_DECLARE_MUTABLE_CF_TYPE) @@ -554,6 +555,7 @@ QT_BEGIN_NAMESPACE } // Defined in qcore_mac_objc.mm +Q_CORE_EXPORT QDebug operator<<(QDebug, id obj); Q_CORE_EXPORT QDebug operator<<(QDebug, const NSObject *); Q_CORE_EXPORT QDebug operator<<(QDebug, CFStringRef); diff --git a/src/corelib/kernel/qcore_mac.mm b/src/corelib/kernel/qcore_mac.mm index 162e55fa0da..a251c51477f 100644 --- a/src/corelib/kernel/qcore_mac.mm +++ b/src/corelib/kernel/qcore_mac.mm @@ -196,6 +196,27 @@ os_log_t AppleUnifiedLogger::cachedLog(const QString &subsystem, const QString & // ------------------------------------------------------------------------- +QDebug operator<<(QDebug dbg, id obj) +{ + if (!obj) { + // Match NSLog + dbg << "(null)"; + return dbg; + } + + for (Class cls = object_getClass(obj); cls; cls = class_getSuperclass(cls)) { + if (cls == NSObject.class) { + dbg << static_cast(obj); + return dbg; + } + } + + // Match NSObject.debugDescription + const QDebugStateSaver saver(dbg); + dbg.nospace() << '<' << object_getClassName(obj) << ": " << static_cast(obj) << '>'; + return dbg; +} + QDebug operator<<(QDebug dbg, const NSObject *nsObject) { return dbg << (nsObject ?