我在 Xcode 项目中遇到了控制台问题。我能够在 Swift 中调试 Swift 单例,但不能在 Xcode 8 和 9、Swift 3 和 4 中调试 Objective-C。
问题是,为什么在调试 Objective-C 类时无法在控制台中打印有问题的值?在 Swift 类中调试时没有问题,控制台甚至自动为我完成 swift 类。
示例类:
Objective-C View Controller
#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 类生成 header
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>
日志输出如下(调试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
最佳答案
您似乎发现了 lldb 中的一个错误。我可能会提交一份关于 http://bugs.swift.org 的错误报告,让开发团队知道。
与此同时,您可以通过在 lldb 控制台中手动指定 Swift 来解决这个问题:
expr -l swift -O -- SOSingleton.instance.apple
或者,如果您需要在 Objective-C 中使用它做一些事情:
expr -l swift -O -- SOSingleton.instance
它将输出类似 <SOQuestion.SOSingleton: 0x0123456789abcdef>
的内容,此时您可以复制十六进制值并执行以下操作:
po [(id)0x0123456789abcdef apple]
关于ios - 无法在 Xcode 控制台中从 Objective-C 记录 Swift 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46432122/