我正在尝试实施令人敬畏的库JSQMessagesViewController,但我不断收到错误"' ModelMessage'不符合协议' JSQMessageData'"即使我的类继承自NSObject并且我实现了所需的属性
以下是协议:
@protocol JSQMessageData <NSObject>
@required
- (NSString *)senderId;
- (NSString *)senderDisplayName;
- (NSDate *)date;
- (BOOL)isMediaMessage;
- (NSUInteger)messageHash;
@optional
- (NSString *)text;
- (id<JSQMessageMediaData>)media;
@end
这是我的班级
import Foundation
class ModelMessage: Model, JSQMessageData {
/* Required */
var senderId: NSString
var senderDisplayName: NSString
var date: NSDate
var isMediaMessage: Bool
var messageHash: UInt
/**/
var text_: String
var id:String!
var conversationId: String!
var imageUrl: String?
var recipientId: String!
var recipientRead: Bool!
var avatar: NSData?
init(data: NSDictionary){
super.init()
/* Required */
self.senderId = getStringFromJSON(data, key:"senderId")
self.senderDisplayName = "Me"
let dateString = getStringFromJSON(data, key: "timeStamp")
let dateDouble = (dateString as NSString).doubleValue / 1000.0
self.date = NSDate(timeIntervalSince1970: dateDouble)
self.isMediaMessage = false
/**/
self.text_ = getStringFromJSON(data, key:"text")
self.id = getStringFromJSON(data, key:"id")
self.conversationId = getStringFromJSON(data, key:"conversationId")
self.recipientId = getStringFromJSON(data, key:"recipientId")
self.recipientRead = data["recipientRead"] as! Bool
}
}
继承自
import Foundation
class Model: NSObject
{
func getStringFromJSON(data: NSDictionary, key: String) -> String {
if let info = data[key] as? String{
return info
}
return ""
}
}
答案 0 :(得分:2)
在实现没有可空性注释的ObjC协议时,尝试使用隐式解包的选项。此外,您可以而且应该始终使用String
代替NSString
。
var senderId: String!
var senderDisplayName: String!
var date: NSDate!
var isMediaMessage: Bool
var messageHash: UInt
使用@objc
注释整个班级和/或属性也可以提供帮助。
如果仍然无效,请检查构建日志,因为它会告诉您哪些协议功能缺失或未正确实现。
答案 1 :(得分:0)
试试这个
import Foundation
class ModelMessage: NSObject , JSQMessageData {
/* Required */
var senderId: NSString
var senderDisplayName: NSString
var date: NSDate
var isMediaMessage: Bool
var messageHash: UInt
/**/
var text_: String
var id:String!
var conversationId: String!
var imageUrl: String?
var recipientId: String!
var recipientRead: Bool!
var avatar: NSData?
init(data: NSDictionary){
super.init()
/* Required */
self.senderId = getStringFromJSON(data, key:"senderId")
self.senderDisplayName = "Me"
let dateString = getStringFromJSON(data, key: "timeStamp")
let dateDouble = (dateString as NSString).doubleValue / 1000.0
self.date = NSDate(timeIntervalSince1970: dateDouble)
self.isMediaMessage = false
/**/
self.text_ = getStringFromJSON(data, key:"text")
self.id = getStringFromJSON(data, key:"id")
self.conversationId = getStringFromJSON(data, key:"conversationId")
self.recipientId = getStringFromJSON(data, key:"recipientId")
self.recipientRead = data["recipientRead"] as! Bool
}
func getStringFromJSON(data: NSDictionary, key: String) -> String {
if let info = data[key] as? String{
return info
}
return ""
}
}