怎么把NSDictonary从Swift转换成Objective-c?

时间:2019-06-09 14:48:41

标签: objective-c swift nsdictionary

我正在跟踪一个聊天应用程序的教程及其快速编写,但是我在Objective-C中进行操作,所以我不知道该如何解决这个问题。

我一直在寻找解决方案,却一无所获,因为我不知道如何处理NSDictionary。

这个想法是,当我收到FIRDatabase的请求时,其中有4个值(fromID,toID,文本和时间戳),ID是指用户,我需要将每个用户的消息(文本)分组在同一键中。这是它的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

import UIKit

class Message: NSObject {

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

}

这是我现在拥有的我的Objective-C代码。

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

#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

- (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;
}

1 个答案:

答案 0 :(得分:0)

在声明了NSArray<Message*>* messages的类中添加新属性NSMutableDictionary<NSString*, Message*>* messagesDictionary- (void)observeMessages。您将获得类似的内容:

@interface MyClass: NSObject

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

- (void)observeMessages;

@end

然后初始化这些属性:

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

删除这些行(我想你也不知道为什么要添加它们):

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

使用此代码将新的Message实例同时添加到messagesmessagesDictionary

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];
}

本文中的所有代码均已在Xcode 10.2.1中进行了测试。