简体   繁体   English

如何将NSDictonary从Swift转换为Objective-c?

[英]How to convert NSDictonary from Swift to Objective-c?

I am following a Tutorial for making a chat application and its written in swift but I am doing it in objective-c, I was not able to figure out how to solve this problem. 我正在关注制作聊天应用程序的教程,并且它是用swift编写的,但是我在objective-c中这样做,我无法弄清楚如何解决这个问题。

I searched for a solution and found nothing because I don't know how to deal with NSDictionary a lot. 我搜索了一个解决方案但没有发现任何东西,因为我不知道如何处理NSDictionary很多。

The idea is when I receive the request from FIRDatabase there is 4 values in it (fromID, toID, text and timestamp) ID's are referred to users and I need to group the messages (text) for each user in the same key. 我的想法是,当我收到来自FIRDatabase的请求时,其中有4个值(fromID,toID,text和timestamp)ID被引用给用户,我需要在同一个密钥中为每个用户分组消息(文本)。 Here is the Swift code for it. 这是它的Swift代码。

viewController.swift viewController.swift

var messages = [Message]()
    var messagesDictionary = [String: Message]()

    func observeMessages() {
        let ref = FIRDatabase.database().refrence().child("messages")
        ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {
            let message = Message()
            message.setValuesForKeysWithDictionary(dictionary)
            self.message.append(message)

            self.messagesDictionary[message.toID] = message

            dispatch_async(dispatch_get_main_queue(), {
                self.tableView.reloadData()
            })
        }
    }, withCancelBlock: nil)

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messages.count
    }

Message.swift Message.swift

import UIKit

class Message: NSObject {

    var fromID: String?
    var text: String?
    var timestamp: NSNumber?
    var toID: String?

}

This is my Objective-C Code I have right now. 这是我现在的Objective-C Code。

HomeViewController.m HomeViewController.m

#import "HomeViewController.h"
#import "messages.h"

@import Firebase;

@interface HomeViewController ()
@property (strong, nonatomic) FIRAuthStateDidChangeListenerHandle handle;
@property (nonatomic, strong) NSMutableArray<messages*> *Messages;
@property (nonatomic, strong) NSMutableDictionary<NSString*, messages*> *messagesDictionary;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.ref = [[FIRDatabase database] referenceFromURL:@"*****"];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    _Messages = [NSMutableArray<messages*> new];
    _messagesDictionary = [NSMutableDictionary<NSString*, messages*> new];

    [self observeMessages];
}

- (void) observeMessages {

    self.ref = [[[FIRDatabase database] reference] child:@"messages"];
    [_ref observeEventType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot *snapshot) {

        NSString *text = [snapshot.value objectForKey:@"Text"];
        NSString *fromID = [snapshot.value objectForKey:@"fromID"];
        NSString *toID = [snapshot.value objectForKey:@"toID"];
        NSString *timestampString = [snapshot.value objectForKey:@"timestamp"];
        //NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
        //NSNumber *timestamp = [formatter numberFromString:timestampString];

        messages *message = [[messages alloc] initWithFromID:fromID andToID:toID andText:text andTimestamp:timestampString];
        [self->_Messages addObject:message];
        self->_messagesDictionary[message.toID] = message;

        dispatch_async(dispatch_get_main_queue(), ^{
            [self->_tableView reloadData];
        });
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {

    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];

    self.ref = [[[[FIRDatabase database] reference]child:@"users"]child:[arrayToID objectAtIndex:indexPath.row]];
    [_ref observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {

        cell.displayName.text = [snapshot.value objectForKey:@"DisplayName"];
    } withCancelBlock:^(NSError *error) {
        //
    }];

    cell.mainLabel.text = [_Messages objectAtIndex:indexPath.row];
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //return arrayText.count;
    return _Messages.count;
}

messages.h messages.h

#import <Foundation/Foundation.h>

@interface messages : NSObject

@property(strong, nonatomic) NSString *text;
@property(strong, nonatomic) NSString *fromID;
@property(strong, nonatomic) NSString *toID;
@property(strong, nonatomic) NSString *timestamp;

- (instancetype)initWithFromID:(NSString *)fromID
                  andToID:(NSString *)toID
                   andText:(NSString *)text
                    andTimestamp:(NSString *)timestamp
                     NS_DESIGNATED_INITIALIZER;

@end

messages.m messages.m

- (instancetype)init {
    return [self initWithFromID:@"" andToID:@"" andText:@"" andTimestamp:@""];
}

- (instancetype)initWithFromID:(NSString *)fromID
                  andToID:(NSString *)toID
                   andText:(NSString *)text
                    andTimestamp:(NSString *)timestamp
                      {
    self = [super init];
    if (self) {
        self.fromID = fromID;
        self.toID = toID;
        self.text = text;
        self.timestamp = timestamp;
    }
    return self;
}

Add new properties NSArray<Message*>* messages and NSMutableDictionary<NSString*, Message*>* messagesDictionary to the class where you declared - (void)observeMessages . 将新属性NSArray<Message*>* messagesNSMutableDictionary<NSString*, Message*>* messagesDictionary到您声明的类- (void)observeMessages You will get something like that: 你会得到类似的东西:

@interface MyClass: NSObject

@property (nonatomic, strong) NSArray<Message*>* messages;
@property (nonatomic, strong) NSMutableDictionary<NSString*, Message*>* messagesDictionary;

- (void)observeMessages;

@end

Then initialise these properties: 然后初始化这些属性:

_messages = [NSArray<Message*> new];
_messagesDictionary = [NSMutableDictionary<NSString*, Message*> new];

Remove these lines (I guess you also don't know why did you add them): 删除这些行(我猜你也不知道为什么要添加它们):

[self->arrayText addObject:text];
[self->arrayFromID addObject:fromID];
[self->arrayToID addObject:toID];
[self->arrayTimestamp addObject:timestampString];

Use this code to add a new Message instance both to messages and messagesDictionary : 使用此代码向messagesmessagesDictionary添加新的Message实例:

Message* message = [[Message alloc] initWithFromID:fromID andToID:toID andText:text andTimestamp:timestampString];
if (message.toID != nil) {
    _messagesDictionary[message.toID] = message;
    _messages = [[NSArray alloc] initWithArray:_messagesDictionary.allValues];
}

All code in this post was tested in Xcode 10.2.1. 本文中的所有代码都在Xcode 10.2.1中进行了测试。

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

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