如何将Swift Controller中的参数传递给目标C模型?

时间:2019-01-19 01:19:01

标签: objective-c swift3

我不知道如何在swift控制器文件中传递String类型的变量并将其传递给用Objective-C编写的对象。但是,如果我直接将字符串作为参数传递,则效果很好。谢谢您的帮助。

这是下面的Objective-C类

#import "Message.h"

@implementation Message

- (instancetype)initWithDictionary:(NSDictionary *)dictionary
{
    self = [super init];
    if (self)
    {
        self.userID = dictionary[@"user_id"];
        self.username = dictionary[@"username"];
        self.avatarURL = dictionary[@"avatar_url"];
        self.text = dictionary[@"message"];
    }

    return self;
}

- (instancetype)initWithTestName:(NSString *)name withTestMessage:(NSString *)message withUserId:(NSString *)userId withAvatarUrl:(NSString *)url
{
    self = [super init];
    if (self)
    {
        self.userID = userId;
        self.username = name;
        self.avatarURL = url;
        self.text = message;
    }

    return self;
}

@end

这是快捷控制器文件

import UIKit

class ChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

private var messages = [Message]()

override func viewDidLoad() {
    super.viewDidLoad()

    // I can pass the string successfully to the messages this way
    messages.append(Message(testName: "Test", withTestMessage: "Hello", withUserId: "1", withAvatarUrl: "http://www.example.com"))

    // After successfully making Api Request, I wasn't able to pass a variable as parameter
     if let data = dic as? [String:Any]{
                    let userId = data["user_id"] as? String
                    let url = data["avatar_url"] as? String
                    let name = data["name"] as? String
                    let message = data["message"] as? String

                    self.messages.append(Message(testName: name, withTestMessage: message, withUserId: userId, withAvatarUrl: url))

                }
     } 
}

0 个答案:

没有答案