无法在 Xcode 控制台中从 Objective-C 记录 Swift Singletons

Posted

技术标签:

【中文标题】无法在 Xcode 控制台中从 Objective-C 记录 Swift Singletons【英文标题】:Can't log Swift Singletons from Objective-C in Xcode Console 【发布时间】:2017-09-26 17:03:36 【问题描述】:

我在 Xcode 的项目中遇到了控制台问题。我能够在 Xcode 8 和 9、Swift 3 和 4 中调试 Swift 内部的 Swift Singleton,但不能调试 Objective-C。

问题是,为什么调试 Objective-C 类的时候不能在控制台打印出问题的值?在 Swift 类中调试时没有问题,控制台甚至为我自动完成了 swift 类。

示例类:

Objective-C 视图控制器

#import "ViewController.h"
#import "SOQuestion-Swift.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad 
    [super viewDidLoad];
    NSLog(@"Property: %@", SOSingleton.instance.appleProperty);
    NSLog(@"Return: %@", [[SOSingleton instance] apple]);
    SOSingleton *so = [SOSingleton instance];
    NSLog(@"Object: %@", so);

Swift 类

import Foundation

@objcMembers
public class SOSingleton: NSObject 

    public static let instance = SOSingleton()

    public override init() 
        super.init()
    

    public func apple() -> String 
        return "apple"
    

    public let appleProperty = "apple"

为 Swift 类生成的标头

SWIFT_CLASS("_TtC10SOQuestion11SOSingleton")
@interface SOSingleton : NSObject
SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly, strong) SOSingleton * _Nonnull instance;)
+ (SOSingleton * _Nonnull)instance SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
- (NSString * _Nonnull)apple SWIFT_WARN_UNUSED_RESULT;
@property (nonatomic, readonly, copy) NSString * _Nonnull appleProperty;
@end

日志输出如下:

Property: apple
Return: apple
Object: <SOQuestion.SOSingleton: 0x60800003e140>

logging的输出如下(调试ViewController时):

(lldb) po [[SOSingleton instance] apple]
Error [IRForTarget]: Couldn't resolve the class for an Objective-C 
static method call
error: The expression could not be prepared to run in the target

【问题讨论】:

Objective-C 没有这样的static methods @NazmulHasan 虽然这是真的,但 Swift static 方法作为 class 方法桥接到 Objective-C,语言确实支持。 【参考方案1】:

您似乎在 lldb 中发现了一个错误。我可能会在 http://bugs.swift.org 上提交错误报告,让开发团队知道。

与此同时,您可以通过在 lldb 控制台中手动指定 Swift 来解决它:

expr -l swift -O -- SOSingleton.instance.apple

或者,如果您需要在 Objective-C 中使用它:

expr -l swift -O -- SOSingleton.instance

这将输出类似&lt;SOQuestion.SOSingleton: 0x0123456789abcdef&gt; 的内容,此时您可以复制十六进制值并执行以下操作:

po [(id)0x0123456789abcdef apple]

【讨论】:

谢谢查尔斯,我会提交报告。上面的表达式示例似乎遇到了类似的问题 - 它返回 error: &lt;EXPR&gt;:3:1: error: use of unresolved identifier 'SOSingleton' 。但是,我能够使用之前记录的值来实现您的 po 示例,所以谢谢! @Breadbin 您可能需要先导入 lldb 才能了解项目中的符号:expr -l swift -- import TheNameOfMyProject

以上是关于无法在 Xcode 控制台中从 Objective-C 记录 Swift Singletons的主要内容,如果未能解决你的问题,请参考以下文章