Objective C 填充向量。 Push_back 不工作

Objective C fill vector. Push_back not working

我是新手 Objetive C 开发人员,我正在尝试填充一个向量,它是一个变量 属性...但是它不起作用,我不明白为什么或如何修复它

-(void) setUpLabels:(NSString *) _labels_path {
    // Read the label list
    self.label_strings.clear();
    std::vector<std::string> new_values;
    std::ifstream t;
    t.open([_labels_path UTF8String]);
    std::string line;
    while (t) {
        std::getline(t, line);
        new_values.push_back(line);
    }
    self.label_strings.reserve(new_values.size());
    for (int index = 0; index  < new_values.size(); index++) {
        self.label_strings.push_back(new_values[index]);
    }
    NSLog(@"size=%lu",self.label_strings.size());
    t.close();

}

这是 .h 文件

@interface AIClassifier: Classifier
@property std::vector<std::string> label_strings;

    - (id) init;
    - (id) initWithParams:(NSString *)model:(NSString *) labels;
@end

函数 setUpLabels 不在文件中..

一直打印 size = 0。我尝试了更简单的版本,结果相同。

此代码的一个问题是您使用了 @propertyself.label_strings@property 创建一个 getter 方法,该方法 returns 类型为 std::vector<std::string> 的值。这是一个值,而不是 pointer/reference,因此它将是基础对象的新副本。这意味着每次调用 self.label_strings.push_back(x) 或任何其他方法时,它都会对初始对象(始终为空)的副本进行操作。

要解决此问题,请使用 _label_strings 而不是 self.label_strings,或者使用 label_strings 的实例变量而不是 @property:

@interface AIClassifier: Classifier {
    std::vector<std::string> label_strings;
}
@end

(注意:最好将其移动为 .mm 文件中的私有实例变量)

如果没有特殊原因要使用 C++ 来完成此任务,有几种 Objective-C 方法可以逐行读取文件。

如果文件很小,你可以将它完全读入内存,然后拆分成单独的行,如下所示:

在 Objective-C 中我们使用 NSArray<NSString*>* 而不是 std::vector<string>

您没有得到任何东西的另一个可能原因是 _labels_path 文件路径错误或设备上不存在。

您可以在此函数中设置一个断点并使用 Xcode 逐步调试器来查看实际发生的情况以及当时在 _labels_path 和 new_values 中的内容执行。

通常您不必在 Objective-C 中使用 C++,尤其是在接口中。如果您将文件设为“.m”而不是“.mm”,它将不允许内部使用 C++(仅 Objective-C)。

注意 1:如果您坚持使用 C++,则不需要第二个循环。只需分配 self.label_strings = new_values; 即可复制它(这是 C++ 的魔法)。

注意2:打开文件后一定要检查一下。在 Objective-C 中,您通常会从函数返回 NSError*。在 C++ 中,您可以检查故障位(参见 open docs example)。

注3:最好使用RAII to make sure that the file is closed. In this case t.close(); is not needed, because ifstream destructor will close it (see http://www.cplusplus.com/reference/fstream/ifstream/close/).