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

标签 objective-c swift nsdictionary

我正在遵循制作聊天应用程序的教程,它是用 swift 编写的,但我是在 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
    }

消息.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;
}

最佳答案

添加新属性 NSArray<Message*>* messagesNSMutableDictionary<NSString*, Message*>* messagesDictionary到您声明 - (void)observeMessages 的类(class)。你会得到类似这样的东西:

@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 中进行了测试。

关于objective-c - 如何将 NSDitonary 从 Swift 转换为 Objective-c?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56515576/

相关文章:

swift - 在 Alamofire 中设置带有嵌套键值的 header

ios - 在 TableView 中显示具有相同键的多个对象

objective-c - CoreData 编辑/覆盖对象

ios - 在 Swift 中找不到自定义类成员

objective-c - 使用 Xcode 4 编译 libogg

ios - 无法将类型 '__NSCFConstantString' 的值转换为 'NSArray'

ios - 使用谓词在数组中搜索字典

ios - Firebase 如何获取 NSDictionary 数据

objective-c - 循环遍历 NSMutableDictionary

ios - 将char数组转换为NSString对象的方式,最后一个字符多一个