繁体   English   中英

为什么 Swift object 在 Objective-C 代码中声明/未声明为属性时表现不同?

[英]Why Swift object behaves differently when it is declared/not declared as property in Objective-C code?

我有一些 Swift class 使用一些库呈现ViewController 这里是:

@objc class FloatingPanelAdapter: NSObject, FloatingPanelControllerDelegate {

@objc func present(vcToBeShown: UIViewController,
                   vcToPresent: UIViewController) {
    // init of panel from library
    let panel = FloatingPanelController()
    // setting vc that I want to display
    panel.set(contentViewController: vcToBeShown)
    // setting delegate
    panel.delegate = self
    // presenting
    vcToPresent.present(panel, animated: true)
}

/// FloatingPanelControllerDelegate method
func floatingPanel(_ vc: FloatingPanelController, layoutFor newCollection: UITraitCollection) -> FloatingPanelLayout? {
    /// FullFloatingLayout is my custom class that implements FloatingPanelLayout. I can show it if you want.
    return FullFloatingLayout()
}
}

以下是我如何使用上面的 class:

- (IBAction)pressed:(id)sender {
   FloatingPanelAdapter *fpAdapter = [[FloatingPanelAdapter alloc] init];
   SomeViewController *vc = [[SomeViewController alloc] init];
   [fpAdapter presentWithVcToBeShown:vc vcToPresent:self];
}

当按钮被按下时,我只是初始化FloatingPanelAdapter并使用它。 SomeViewController已成功呈现,但配置不正确。 它以FloatingPanel库的默认布局(不是我的FullFloatingLayout )呈现。 但神奇的是当我将我的fpAdapter声明为一个属性时:

#import "ViewController.h"
/* --- Importing Swift into Objective-C -- */
#import "SamplesObjC-Swift.h"
/* --------------------------------------- */
@interface ViewController ()
@property FloatingPanelAdapter *fpAdapter;
@end

@implementation ViewController

- (IBAction)pressed:(id)sender {
   self.fpAdapter = [[FloatingPanelAdapter alloc] init];
   SomeViewController *vc = [[SomeViewController alloc] init];
   [self.fpAdapter presentWithVcToBeShown:vc vcToPresent:self];
}
@end

现在我的SomeViewController已完全呈现,并通过FullFloatingLayout进行了正确的配置。 我不会在这里留下屏幕截图,因为这无关紧要。 我认为问题是我没有在这里正确使用 Objective-C(我不太了解)。 为什么它的行为不同? 可能是什么问题?

我认为问题是我没有在这里正确使用 Objective-C(我不太了解)。 为什么它的行为不同? 可能是什么问题?

不它不是。 问题出在memory管理。

- (IBAction)pressed:(id)sender {
   // here fpAdapter is created locally, so on quit this context it is destroyed
   FloatingPanelAdapter *fpAdapter = [[FloatingPanelAdapter alloc] init];
   SomeViewController *vc = [[SomeViewController alloc] init];
   [fpAdapter presentWithVcToBeShown:vc vcToPresent:self];
}
// >> here fpAdapter.dealloc

一旦fpAdapter被销毁,面板的delegate就变为nil ,因为它weak ,所以不会保留fpAdapter的引用

    panel.delegate = self     // << here !!

因此,要进行delegate工作,您必须在panel的生命周期中保持fpAdapter处于活动状态。 并使其成为财产正是这样做的

@interface ViewController ()
   @property FloatingPanelAdapter *fpAdapter;  // << keeps strong reference

尽管如此,但您必须在某处保留对fpAdapter的引用!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM