加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

建议使用Objective-C类的C类最小化使用Objective-C?

发布时间:2020-12-16 04:55:55 所属栏目:百科 来源:网络整理
导读:我正在混合Objective-C和C.但是我想尽量减少使用Objective-C.因为它在Objective-C和C中都有某种限制. 目前,我正在使用它. // A.h,Objective-C#import "B.h"@interface A{ B* b;}@end// B.h,Objective-C++@interface B{ void* c;}// C.h,C++class C{}; 我想把
我正在混合Objective-C和C.但是我想尽量减少使用Objective-C.因为它在Objective-C和C中都有某种限制.

目前,我正在使用它.

// A.h,Objective-C
#import "B.h"
@interface A
{
    B* b;
}
@end

// B.h,Objective-C++
@interface B
{
    void* c;
}

// C.h,C++
class C
{
};

我想把C.h包括在B.h中,但如果我这样做,那么B.h就不能被导入A.h.所以我必须将变量c保留为void *类型.这不是一个大问题,因为我可以自由地使用B.m文件中的C成员.但我总是要施展它.这感觉不清楚.所以我想用更好的方法.

解决方法

有几种方法可以做到这一点,但在我看来,最好的方法是使用 ‘PIMPL’ idiom,这在C中很常见.使标头纯粹是Objective-C和纯C,带有指向包含实际实现的前向声明结构的指针.这是在.mm文件中定义的,然后可以使用Objective-C.

在您的示例中,您将执行以下操作:

// B.h,pure Objective-C:
struct BImpl;
@interface B
{
    struct BImpl* impl;
}
// ...


// B.mm,mixed:
#include "C.h"
struct BImpl // since this is C++,it can actually have constructors/destructors
{
    C* my_c;
    BImpl() : my_c(new C) {}
    ~BImpl() { delete my_c; my_c = NULL; }
};
// make sure to alloc/initialise impl (using new) in B's init* methods,// and free it (using delete) in the dealloc method.

我实际上写了一篇关于解决这个问题的文章,你可能会发现它很有用:http://philjordan.eu/article/strategies-for-using-c++-in-objective-c-projects – 它还展示了其他一些方法,包括你原来的void *方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读