【问题标题】:Needing to wrap a large chunk of C code in an Objective-C method需要在 Objective-C 方法中包装大量 C 代码
【发布时间】:2014-03-11 15:09:04
【问题描述】:

我有一段用 C 语言编写的从设备中提取数据的代码,可以查看该代码Here

我希望这个包含一个名为 getData 的函数的代码作为 Objective-C 类的方法(称为 getData)运行,而不是像现在在我测试它时那样让它从 main() C 函数内部运行出去。我的目标是让这个方法填充一个公共全局变量变量,甚至只是一个带有 base64 编码字符串的类属性并返回一个状态。

这是我目前的设置方式,但这也是我第一次同时编写 C 和 Objective-C,所以说实话,我不确定我的方法是否正确。首先,我创建了一个名为 GDDriver.h 的接口(协议)

//GDDriver.h
typedef enum Status : NSInteger {
    Success,
    Cancelled,
    DeviceNotFound,
    DeviceError,
    UnkownModel,
} Status;

@protocol GWDriver <NSObject>

-(enum Status)getData;
-(void)cancel;

@end

然后我有一个类,可以称之为 DriverOne,我正在这样设置

DriverOne.h

// DriverOne.h
#import <Foundation/Foundation.h>
#import "GWDriver.h"

@interface DriverOne : NSObject <GWDriver>

@end

DriverOne.m

// DriverOne.m
#import "DriverOne.h"

@implementation DriverOne

enum Status getData(char* encodedBuffer, int user)
{
    // Copy C code which I showed in the link earlier
    // into this method. I will want it to return a status
    // and populate a global variable with the data.
}


void cancel()
{
    // Cancels and closes driver
    // is called from with in getData()
}

@end

我知道这里的方法目前是用 C 语法编写的,但我不确定这是否是不好的做法。这是我打算如何调用该方法。

DriverOne *driver = [[DriverOne alloc] init];
driver.getData();  

我在这里完全偏离了基础,还是这种方法在我想要实现的目标中是正确的? 感谢您的任何意见或建议。

【问题讨论】:

  • 你不只是在另一个问题中问这个问题吗:stackoverflow.com/questions/22334819/…
  • 这感觉太笼统了,所以不是 codereview xchg 或程序员 xchg
  • @Daij-Djan 下次我将使用 SE Codereview 解决此类问题,谢谢。

标签: objective-c c oop


【解决方案1】:

最佳实践要求您通常不在您的 Objective C 类中使用 C 风格的函数。 char 指针通常也不受欢迎。我会把你的功能改成这样:

- (enum Status)getDataWithBuffer:(NSString *)buffer userId:(NSInteger)userId
{
    char * encodedBuffer = [buffer UTF8String];

    // Copy C code which I showed in the link earlier
    // into this method. I will want it to return a status
    // and populate a global variable with the data.
}


- (void)cancel
{
    // Cancels and closes driver
    // is called from with in getData()
}

然后把你的电话改成这个

DriverOne *driver = [[DriverOne alloc] init];
[driver getData:@"your data" userId:12345]; 

【讨论】:

  • 如果我在 DriverOne 类上设置一个属性,即使 getData 返回 void,我是否能够用 getData 接收的数据填充它?它实际上是获取字节数组缓冲区并将其转换为字符串,然后再转换为 Base64 字符串。
  • 是的,你完全可以做到。 NSData 可能是您将其存储在其中的内容。我想这取决于您使用它做什么。
  • 很高兴知道!驱动方法实际上是从按钮事件中调用的,然后存储在属性中的数据将被发送到解析器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 2014-04-27
  • 1970-01-01
  • 2014-08-26
  • 1970-01-01
相关资源
最近更新 更多