从 Objc 超类继承的 Swift 子类中未调用 viewDidLoad
Posted
技术标签:
【中文标题】从 Objc 超类继承的 Swift 子类中未调用 viewDidLoad【英文标题】:viewDidLoad not being called in Swift subclasses inherited from Objc superclass 【发布时间】:2020-06-29 20:30:12 【问题描述】:我有一个关于 Objc 与 Swift 中的 viewDidLoad 的问题。我不是 熟悉 Swift,第一次尝试将 Swift 代码嵌入到我们的应用中。
我试图嵌入的 swift 代码有两个以这种方式声明的继承类:
ViewController_A (swift) : ViewController_B (swift) : UIViewController
视图控制器 A 和 B 都有“覆盖”viewDidLoad
方法。
也就是说,它们被声明为override func viewDidLoad()
。如果
我保留上述关系,并设置断点并运行
ViewController_A
和 ViewController_B
的 viewDidLoad
中的 print
语句,
我确实看到viewDidLoad
for ViewController_A
在viewDidLoad
for
viewController_B
。这似乎完全有道理。两者各自
viewDidLoad
方法调用 super.viewDidLoad
。一切都很好。
我尝试通过添加一个 链中的 Objective-C 类:
ViewContoller_A
(Swift):ViewController_B
(Swift):ViewController_C
(Objective-C):UIViewController
。
ViewController_C
也有一个viewDidLoad
方法,它也调用[super viewDidLoad]
。
如果我在所有三个视图控制器中的所有三个viewDidLoad
方法的开头设置断点和print
s/NSLog
运行,则只有viewDidLoad
用于ViewController_C
(Objective-C)
执行。控制器 A 和 B viewDidLoad
中的断点/print
s 永远不会出现。我不确定这是否会在主题中添加不必要的信息,但有趣的是我会收到一条警告消息:
尝试在视图不在视图中的 ViewController_C 上呈现 ViewController_A 窗口层次结构!
这似乎告诉我ViewController_A
正在尝试加载视图。所以为了确定,作为测试,我注释掉了ViewContoller_C
viewDidLoad
中所有与UI相关的代码。然后我没有收到该警告消息,它不应该阻止 ViewController_A
viewDidLoad
执行,但 ViewController_A
中的 viewDidLoad
方法仍然没有。
注意,ViewController_C
是由模态故事板 segue 提出的,如果它添加了任何相关信息。
很抱歉所有这些杂乱无章,但是有没有办法强制 Swift 子类视图控制器中的 viewDidLoad
方法在我上面概述的类继承层次结构中执行,并添加了 Objective-C 视图控制器?
感谢您的帮助, 迈克
感谢您的回复。我在下面添加了一些代码供您查看。如果我可以添加任何其他内容,请告诉我。也许简要概述会有所帮助。
我添加的应用程序代码集代表了一个条形码扫描控制器,我们使用它来读取样品瓶中的条形码标签。该代码在 objc 中。客户现在希望在相同的操作环境中读取文本代码。因此,在短期内,我将切碎条码扫描控制器以开始工作。
对于这个项目,我引入了一个由 Apple 编写的示例应用程序,可从他们的 WWDC 会议中下载,用于读取/识别电话号码。那是用swift编写的代码。到目前为止,我对这段代码做了一些小的修改。
一旦克服了技术障碍,我将重写两者。
BarCodeScan .h 和 .m 文件的开头:
#ifndef _BARCODESCANNERCONTROLLER_H_
#define _BARCODESCANNERCONTROLLER_H_
#import <UIKit/UIKit.h>
#import "SystemHeader.h"
#import "RunParameters.h"
#import <RDPDFKit/RDPDFKit.h>
#import "FormInfo.h"
#import "PatientInfo.h"
#import "GradientButton.h"
#import "LogTextInfo.h"
#import "Fileiosupport.h"
#import "PadInfo.h"
#import "XMLiPadAndDBSupport.h"
#import "BarCodeScanSupport.h"
#import "LogonInfo.h"
#import "PadInfo.h" // ocr
#import "TextScanPreviewView.h" // ocr
#define YesIndex 0
//
// With PDF coordintates, pixels are spot on so no shift
// is needed. Keep these at 0 for now.
//
#define SCALE_Y_ADJUSTMENT_FACTOR 0
#define SCALE_X_ADJUSTMENT_FACTOR 0
#define XML_VERSION_STR "<?xml version=\"1.0\"?>"
#define XML_HEADER_NAME "IFD"
#define ResultCount "ResultCount"
#define Result "Result"
#define DoNotCheck @"DoNotCheck"
#define DoNotValidate @"DoNotValidate"
//
// These enums are for determining the action needed when
// an incorrect but valid bar code is scanned.
//
//
// These enums are for determining the action needed when
// an incorrect but valid bar code is scanned.
//
typedef enum IncorrectBarCodeStatusEnum
BCNotRecognized = 1,
BCNotUsedButBelongsToAnotherForm,
BCAlreadyUsedByAnotherForm,
BCIsOK
IncorrectBarCodeStatusEnum;
@interface ReturnResultBarCodeStatus : NSObject
@property (strong, nonatomic) FormInfo * formWhereBarCodeFound;
@property (assign, nonatomic) IncorrectBarCodeStatusEnum incorrectBarCodeStatus;
@end
@interface BarCodeScanController : UIViewController <UIAlertViewDelegate> // Merck2
BOOL isScanModeOn;
UIColor *borderColorDefault;
UIColor *viewBackgroundColorDefault;
CGPoint lineStartingPoint;
CGPoint lineEndingPoint;
int barCodeImageViewUpperYCoordinate;
DecoderResult * decoder;
// ocr
NSString * textScanResult;
//
// This contains this page's pixel values that are read
// from the xml incoming DBToPad file.
//
@property (strong, nonatomic) Barcode * barCode;
@property (strong, nonatomic) PatientInfo * patient;
@property (strong, nonatomic) FormInfo * form;
@property (strong, atomic) PadInfo * pad;
@property (strong, atomic) LogonInfo * logon;
@property (strong, nonatomic) RDPDFDocument * pdfDocument;
@property (strong, nonatomic) RDPDFDocumentView *pdfDocumentView;
@property (strong, nonatomic) IBOutlet UIImageView * barCodeImageView;
@property (strong, nonatomic) IBOutlet TextScanPreviewView * previewView3;
@property (strong, nonatomic) IBOutlet UIView * cutoutView;
@property (weak, nonatomic) IBOutlet GradientButton *submitButton;
- (IBAction)submitButtonAction:(GradientButton *)sender;
@property (weak, nonatomic) IBOutlet GradientButton *cancelButton;
- (IBAction)cancelButtonAction:(GradientButton *)sender;
@property (weak, nonatomic) IBOutlet GradientButton *scanButton;
- (IBAction)scanButtonAction:(GradientButton *)sender;
@property (weak, nonatomic) IBOutlet UILabel *formLabel;
@property (weak, nonatomic) IBOutlet UILabel *barCodeResultLabel;
@property (strong, nonatomic) BarCodeScanSupport *barCodeScanner;
@property (strong, nonatomic) NSMutableArray *uniqueBarCodes;
- (void) writeBarCodeResultsToXMLDataFile : (BOOL) dataFlag;
- (void) determineIncorrectBarCodeCase
: (NSString *) barCodeResult
: (ReturnResultBarCodeStatus *) returnStatus;
- (void) continueDecodeResultNotification;
@end
#endif
`````` Controller "C"
#import "BarCodeScanController.h"
@implementation ReturnResultBarCodeStatus
@synthesize formWhereBarCodeFound;
@synthesize incorrectBarCodeStatus;
@end
@implementation BarCodeScanController : UIViewController
@synthesize barCode;
@synthesize form;
@synthesize pad;
@synthesize logon;
@synthesize submitButton;
@synthesize cancelButton;
@synthesize scanButton;
@synthesize barCodeImageView;
@synthesize previewView3;
@synthesize cutoutView;
@synthesize pdfDocument;
@synthesize pdfDocumentView;
@synthesize barCodeScanner;
@synthesize uniqueBarCodes;
@synthesize barCodeResultLabel;
@synthesize formLabel;
//
// This is temporary for the demo. Should read whats in the file
// if we scanned on a page, srolled to another, and came back to
// the scanned page. But for now, just .
//
static NSString * saveBarCodeResult;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
// Custom initialization
return self;
- (void)viewDidLoad
[NSThread sleepForTimeInterval : 2.0];
[super viewDidLoad];
if (deviceIsIPad)
self.formLabel.text = [NSString stringWithFormat:
@"%@",form.form];
else
self.formLabel.text = [NSString stringWithFormat:
@" %@",form.form];
[self.cancelButton useAlertStyle];
[self.submitButton useAlertStyle];
[self.scanButton useAlertStyle];
if (self.form.displaySubmitButton == NO)
self.submitButton.hidden = YES;
else
self.submitButton.hidden = NO;
//
// This creates an .ifd file with no data in it. The data base server requires
// a file with valid data or null data for each vas page. So if the user
// evenutally enters valid data, it will overwrite this. Creating the file here
// is completely dependent on the user having to scroll to the end of the form
// to do a submit. In doing so, every vas page must be passed along the way
// which will initiate this call. If we ever go back to starting out with a
// submit button on every page when the form is brought up, then we will have
// to create a null .ifd file in the forms modal controller, which will mean
// we will have to have duplicate functionality in both that controller and
// this one. Note, later added code made sure file does not first exist. It
// may already be there if there was a crash during the submit. In this case
// don't write a null file, and set vsLineDrawn to YES.
//
//
FileIOSupport * sandbox = [[FileIOSupport alloc] init];
if (![sandbox checkIfFileExistsAtPath : self.barCode.bcPngPathNameData])
[self writeBarCodeResultsToXMLDataFile : NO];
[[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(decodeResultNotification:) name: BarCodeResultNotification object: nil];
// ocr x
// Comment out for text reader.
// barCodeScanner = [[BarCodeScanSupport alloc] init : barCodeImageView : self
// : self.barCode.bcFormat];
// ocr x
// Comment out for text reader
// self.barCodeImageView.image = [UIImage imageWithContentsOfFile :
// barCode.bcPngPathNameImage];
[scanButton setTitle:Retry_Str forState:UIControlStateNormal];
//
// Setting isScanModeOn works for both cases below. If we have a prior
// result we don't start the scanner but put up the previous result and
// image. If there is no prior result, we call the scanButtonAction code
// to start the scanner.
//
isScanModeOn = NO;
if (self.barCode.bcImageBuffer != nil)
self.barCodeResultLabel.hidden = NO;
self.barCodeResultLabel.text = barCode.bcSelectedResult;
self.barCodeResultLabel.backgroundColor = [UIColor yellowColor];
else
self.barCodeResultLabel.hidden = YES;
self.barCodeResultLabel.text = Blank;
//
// Start scanner
//
[self scanButtonAction : scanButton];
// ocr
// This normally gets allocatd in bar code scanner support which we are not
// using for ocr. So allocate it here. We're only using the text part of it
// so as to not disturb alot of code.
//
decoder = [DecoderResult alloc];
// ocr
// Comment out for text reader
// barCodeImageViewUpperYCoordinate = self.barCodeImageView.frame.origin.y;
DISPATCH_TO_MAIN_THREAD
// ocr x
// Comment out for text reader
// [self startScanning];
// [self performSegueWithIdentifier:TextReaderModalSegue sender:self];
DISPATCH_OUT_OF_MAIN_THREAD
.
.
.
Project-Bridging-Header.h 的内容
// ocr
#import "ObjectiveCTestWithSwift.h"
#import "BarCodeScanController.h"
#import "TextScanPreviewView.h"
Apple 的控制器之一 - 控制器“B”。注意我试过 viewDidLoad 有“public”关键字,没有。
import UIKit
import AVFoundation
import Vision
// ocr
// class TextReaderViewController: UIViewController
class TextReaderViewController : BarCodeScanController
// MARK: - UI objects
//
// ocr
// Comment these out. These outlets will be provided by barcodescancontroller.
// @IBOutlet weak var cutoutView: UIView!
// @IBOutlet weak var previewView: PreviewView!
@IBOutlet weak var numberView: UILabel!
var maskLayer = CAShapeLayer()
// Device orientation. Updated whenever the orientation changes to a
// different supported orientation.
var currentOrientation = UIDeviceOrientation.portrait
// MARK: - Capture related objects
private let captureSession = AVCaptureSession()
let captureSessionQueue = DispatchQueue(label: "com.example.apple-samplecode.CaptureSessionQueue")
var captureDevice: AVCaptureDevice?
var videoDataOutput = AVCaptureVideoDataOutput()
let videoDataOutputQueue = DispatchQueue(label: "com.example.apple-samplecode.VideoDataOutputQueue")
// MARK: - Region of interest (ROI) and text orientation
// Region of video data output buffer that recognition should be run on.
// Gets recalculated once the bounds of the preview layer are known.
var regionOfInterest = CGRect(x: 0, y: 0, width: 1, height: 1)
// Orientation of text to search for in the region of interest.
var textOrientation = CGImagePropertyOrientation.up
// MARK: - Coordinate transforms
var bufferAspectRatio: Double!
// Transform from UI orientation to buffer orientation.
var uiRotationTransform = CGAffineTransform.identity
// Transform bottom-left coordinates to top-left.
var bottomToTopTransform = CGAffineTransform(scaleX: 1, y: -1).translatedBy(x: 0, y: -1)
// Transform coordinates in ROI to global coordinates (still normalized).
var roiToGlobalTransform = CGAffineTransform.identity
// Vision -> AVF coordinate transform.
var visionToAVFTransform = CGAffineTransform.identity
// MARK: - View controller methods
// ocr
public override func viewDidLoad()
// ocr
print("viewDidLoad TextReaderViewController")
// ocr x
super.viewDidLoad()
// Set up preview view.
previewView3.session = captureSession
// Set up cutout view.
cutoutView.backgroundColor = UIColor.gray.withAlphaComponent(0.5)
maskLayer.backgroundColor = UIColor.clear.cgColor
maskLayer.fillRule = .evenOdd
cutoutView.layer.mask = maskLayer
// Starting the capture session is a blocking call. Perform setup using
// a dedicated serial dispatch queue to prevent blocking the main thread.
captureSessionQueue.async
self.setupCamera()
// Calculate region of interest now that the camera is setup.
DispatchQueue.main.async
// Figure out initial ROI.
self.calculateRegionOfInterest()
// ocr
// super.viewDidLoad()
.
.
.
2nd of Apples Controller "A". Note I tried viewDidLoad
with "public" keyword and without.
import Foundation
import UIKit
import AVFoundation
import Vision
// ocr
// class VisionViewController: ViewController
class VisionViewController: TextReaderViewController
var request: VNRecognizeTextRequest!
// Temporal string tracker
let numberTracker = StringTracker()
public override func viewDidLoad()
// Set up vision request before letting ViewController set up the camera
// so that it exists when the first buffer is received.
// ocr
print("viewDidLoad VisionViewController")
request = VNRecognizeTextRequest(completionHandler: recognizeTextHandler)
super.viewDidLoad()
.
.
.
【问题讨论】:
请发布您的验证码 它与您对 swift 或(更有可能)objective-c 控制器(即 ViewContoller_C)的具体实现有关。所以真的需要这些控制器的代码 @Kiril S. 您好,您要求发布代码。如果你有机会,你能看看我添加了什么吗?谢谢。迈克 @Ol Sen,谢谢您的回复。我不确定你的意思是什么定义。在 Project-Bridging-Swift.h 中,我导入了 BarCodeScannerController.h 来进行我需要的子类化。如果我在 BarCodeScannerControoler.m 中导入 Project-Swift.h,我将获得循环依赖并且无法构建。你指的是那个还是别的什么?再次感谢。迈克 【参考方案1】:在
@interface BarCodeScanController : UIViewController
// place a definition, so swift (Xcode) can see it.
-(void)viewDidLoad;
@end
【讨论】:
【参考方案2】:我发现我的 perform segue 正在执行错误的视图控制器。一旦我纠正了这一点,viewDidLoad 就会以正确的顺序执行。
【讨论】:
以上是关于从 Objc 超类继承的 Swift 子类中未调用 viewDidLoad的主要内容,如果未能解决你的问题,请参考以下文章
`attemptRecovery(fromError:optionIndex:)` 在 NSDocument 的 Swift 子类的超类中找不到