1

刚刚掌握了 Combine 并遇到了一个问题,当它从 a 接收到值时,我需要在我的类中调用一个方法Publisher,在这种情况下是 a Notificationfrom NotificationCenter...

这是订阅...

let subscribe = NotificationCenter.default.publisher(for: Notification.Name(rawValue: "LocalTalkNotificationReceivedData"), object: nil)
    .map( {
        ($0.object as! Data)
    } )
    .sink(receiveValue: {
        self.interpretIncoming(data: $0)
    })

编译器告诉我的是Use of unresolved identifier 'self'. 时间不早了,有点累了,有大神知道吗?Xcode 11 beta 5 on Catalina beta 5 btw ...

完整文件:

import Foundation
import Combine
import SwiftUI

public class MessageData: ObservableObject, Identifiable {
public var peerData: [Peer] = [Peer]()
public var messageData: [Message] = [Message]()
public var objectWillChange = PassthroughSubject<Void, Never>()
let subscribe = NotificationCenter.default.publisher(for: Notification.Name(rawValue: "LocalTalkNotificationReceivedData"), object: nil)
    .map( {
        ($0.object as! Data)
    } )
    .sink(receiveValue: {
        self.interpretIncoming(data: $0)
    })

init() {
    self.setupDummyData()
}

private func setupDummyData() {
    self.peerData = self.load("peerData.json")
    self.messageData = self.load("messageData.json")
}

func addMessage(message: String, sender: MessageSource, name: String) {
    let newMessage = Message(id: Date().hashValue,
                             content: message,
                             source: sender,
                             correspondent: name)
    self.messageData.append(newMessage)
    self.objectWillChange.send()
}

func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
    let data: Data

    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            fatalError("Couldn't find \(filename) in main bundle.")
    }

    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
    }

    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}

func interpretIncoming(data sent: Data) {
    do {
        let receivedTransmission = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(sent) as! [String: Any]
        self.addMessage(message: receivedTransmission["messagePayload"] as! String,
                        sender: .them,
                        name: receivedTransmission["messageSender"] as! String)
    } catch {
        print("FAILED DECODING THING")
    }
}

}

4

2 回答 2

1

Self 在您调用的上下文中不存在。解决这个问题的方法有很多,包括将 translateIncoming 定义为闭包变量或将其设为类方法并根据需要调用。

于 2019-08-10T23:11:06.377 回答
1

除了这个词之外,您问题中的所有内容都是一条红鲱鱼self。你是说:

class MessageData: ObservableObject, Identifiable {
    let subscribe = ... self ...
}

您不能self在属性声明的初始化程序中提及,因为这self是我们正在初始化的过程;还没有self

这里一个简单的解决方案可能是更改let subscribelazy var subscribe,但是您必须subscribe在实际代码中询问 的值才能进行初始化。但是,还有许多其他可能的方法。

于 2019-08-11T15:24:11.173 回答