2

对于一个已经很广泛的 Objective-C 应用程序,我想添加 Core Data 功能。最近在 Swift 中添加了新功能,到目前为止效果很好。

因为我的 Objective-CAppDelegate已经包含了很多东西,所以我决定写一个 Swift 扩展来AppDelegate. 我发现 Objective-C 和 Swift 部分都可以非常愉快地一起生活,除了以下几点。

我从一个空的 Swift Core Data 项目的 Swift 模板中复制的核心数据内容。

问题在于一个可选方法applicationShouldTerminate:(来自NSApplicationDelegate协议),我没有在类的遗留 Objective-C 部分中定义它。但是 Swift 扩展中的定义不会编译,因为该方法似乎是双重定义的。显然,没有提及 Obj-C 源代码中的可选方法会导致包含默认版本。

我试图applicationShouldTerminate:在 Obj-C 中实现一个在 Swift 中调用的虚拟对象applicationShouldterminate2(sender),但是 Obj-C 没有看到扩展中的方法。有没有办法@objc让我可以使符号可见?

关于我应该如何进行的任何提示?

重要的是要知道,我的带有 Core Data 内容的 Swift 扩展最初编译得很好。当我升级到 XCode 6.3b2(我认为)时,符号冲突首先发生。在没有冲突之前。我现在在 XCode 7b1,但仍然没有雪茄。

编辑:添加源代码
文件“AppDelegate.h”:

#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
//stuff for swift extension
  NSPersistentStoreCoordinator *_pSCo;
  NSManagedObjectContext *_mOC;
}
-(NSString *)diag_mOC_descr;
@property (strong) IBOutlet NSPanel *window;
...
#pragma mark for Swift Core Data extension (workaround for iVars)
@property (strong) NSPersistentStoreCoordinator *pSCo;
@property (strong) NSManagedObjectContext *mOC;
@end

文件“AppDelegate.m”

#import "AppDelegate.h"
#import "MainWindowController.h"
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { ... }

// allow Core Data in Swift
-(NSString *)diag_mOC_descr { return _mOC.description; } //diag to test whether _mOC is used by property
...
//properties
@synthesize window = _window;
...
// See swift extension for CoreData stuff
@end

AppDelegate+CD.Swift

import Foundation
extension AppDelegate {
  ...
  // MARK: - Core Data stack
  func applicationDocumentsDirectory () -> NSURL  {...}
  ... //all the regular methods from the swift Core Data stuff ending in:
  func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { ...
  }
}

NSApplicationDelegate 协议有如下定义

SWIFT
optional func applicationShouldTerminate(_ sender: NSApplication) -> NSApplicationTerminateReply
OBJECTIVE-C
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender

错误信息:

/Volumes/.../AppDelegate+CD.swift:150:8: Method 'applicationShouldTerminate' with Objective-C selector 'applicationShouldTerminate:' conflicts with previous declaration with the same Objective-C selector

我认为,自从 XCode6.3b2 以来,编译器生成了一个默认的“ applicationShouldTerminate:”定义,而之前没有。
我目前的解决方法是完全注释掉func applictionShouldTerminate {...}(我预计不会有什么危害,因为我以只读方式访问 CD 数据——CD 数据是由另一个应用程序写入的)。但是,可能有更好的解决方法。

4

0 回答 0