最近,在iOS上调试一个App,核心代码是用C++实现的,App界面使用Object C实现,在XCode下混合编译 C++/Object-C遇到的问题总结一下:
1. 文件格式问题,C++里的.h和.cpp,需要将.cpp改写为.m格式;
2.接口函数:用NSObject封装c++类;
3.混合编译之前一定要把编译器的Compile Sources As选项改为Objective C++;
4.读取txt文件:
filePath = [[NSBundle mainBundle] pathForResource:@"templates" ofType:@"xml"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
5.OS10和之前版本,接口函数上的写法上有些区别。
//
// Created by wang on 11/6/16.
//
// MixCompileTest Object C 和 C++
//
#ifndef GRAPH_SPARSEGRAPH_H
#define GRAPH_SPARSEGRAPH_H
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
// 稀疏图 - 邻接表
class SparseGraph {
private:
int n, m; // 节点数和边数
bool directed; // 是否为有向图
vector<vector<int>> g; // 图的具体数据
public:
// 构造函数
SparseGraph(int n, bool directed) {
assert(n >= 0);
this->n = n;
this->m = 0; // 初始化没有任何边
this->directed = directed;
// g初始化为n个空的vector, 表示每一个g[i]都为空, 即没有任和边
g = vector<vector<int>>(n, vector<int>());
}
~SparseGraph() { }
// 向图中添加一个边
void addEdge(int v, int w) {
assert(v >= 0 && v < n);
assert(w >= 0 && w < n);
g[v].push_back(w);
if (v != w && !directed)
g[w].push_back(v);
m++;
}
// 验证图中是否有从v到w的边
bool hasEdge(int v, int w) {
assert(v >= 0 && v < n);
assert(w >= 0 && w < n);
for (int i = 0; i < g[v].size(); i++)
if (g[v][i] == w)
return true;
return false;
}
// 显示图的信息
void show() {
for (int i = 0; i < n; i++) {
cout << "vertex " << i << ":\t";
for (int j = 0; j < g[i].size(); j++)
cout << g[i][j] << "\t";
cout << endl;
}
}
};
#endif //GRAPH_SPARSEGRAPH_H
Object C和C++适配函数:Xcode下创建新的.h和.mm文件。
//
// ObjectiveCAdaptor.h
// MixCompileTest
//
// Created by wang on 11-4-17.
//
#import <Foundation/Foundation.h>
class SparseGraph; //这个声明得小心,千万不要写成@class
//-- new
@interface ObjectiveCAdaptor : NSObject {
- (void) objectiveFunc;
@end
.mm文件
//
// ObjectiveCAdaptor.m
// MixCompileTest
//
// Created by wang on 11-4-17
//
#import "ObjectiveCAdaptor.h"
#include "SparseGraph.h"
//---new
@implementation ObjectiveCAdaptor{
SparseGraph* testObj;
}
- (id) init {
if (self = [super init]) {
testObj = new SparseGraph();
}
return self;
}
- (void) dealloc {
if (testObj != NULL) {
delete testObj;
testObj = NULL;
}
[super dealloc];
}
- (void) objectiveFunc
{
testObj->show();
testObj->hasEdge(4, 7);
}
@end
//调用示例:
- (void) callObjectiveCAdaptorMethod
{
ObjectiveCAdaptor *testObjectiveCObj = [[ObjectiveCAdaptor alloc] init];
[testObjectiveCObj objectiveFunc];
}
Xcode生成iOS APP里,Object C读取txt文件,需要采用OC读取方法:
NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:@"Demo.txt" ofType:nil];
NSData *xmlData = [NSData dataWithContentsOfFile:xmlFilePath];
OK ,上述是调试iOS App,针对Objective-C和C++混合编程遇到的问题。
解决了接口问题,接下来,就是完善核心代码和iOS界面设计等问题了。
--------------------------------------------------------------------------------------------------------
新的问题,数字和汉字之间的映射关系。比如,地铁路线,我们采用数字编号,用户界面需要输入的是站名(汉字)。
比较通用的方法,是数据库,还有,就是利用强大的iOS数据结构了。
参考文章:
https://www.cnblogs.com/biosli/archive/2011/04/30/Mixing_ObjectiveC_and_Cplusplus_in_iPhone_Development.html