【发布时间】:2016-06-18 08:00:48
【问题描述】:
我正在开发一个使用 OpenCV 的项目,这迫使我将一些分支扩展到 C++ 和 Objective-C。我构建了一个小的 Objective-C 类,它从 OpenCV 框架调用 Objective C++ 函数,并将其桥接到 Swift。
在objective-c 类中,我有一些我希望能够从UI 更改的NSInteger 成员。但是当我尝试获取或设置它们时,它会因熟悉的unexpectedly found nil while unwrapping an Optional value 而崩溃。
我毫不怀疑这是一个基本错误,但我一直在旋转我的轮子,但在缩小范围时遇到了麻烦。如果有人可以看看我的课并告诉我出了什么问题,那就太好了。
.h 文件 @interface OpenCVWrapper : NSObject
// This is a singleton for providing global access to the OpenCV Wrapper
+ (OpenCVWrapper *)sharedInstance;
- (UIImage *)processImageWithOpenCV:(UIImage*)inputImage;
- (void)setupVideoCamera:(UIView*) parentView;
// Filtering properties
@property (atomic, assign) NSInteger hMin;
@property (nonatomic, assign) NSInteger hMax;
@property (nonatomic, assign) NSInteger sMin;
@property (nonatomic, assign) NSInteger sMax;
@property (nonatomic, assign) NSInteger vMin;
@property (nonatomic, assign) NSInteger vMax;
#ifdef __cplusplus
@property (nonatomic, retain) CvVideoCamera* videoCamera;
@property (nonatomic, retain) VideoHandler* videoHandler;
#endif
@end
.mm 文件
@implementation OpenCVWrapper : NSObject
@synthesize videoHandler;
@synthesize videoCamera;
@synthesize hMin;
@synthesize hMax;
@synthesize sMin;
@synthesize sMax;
@synthesize vMin;
@synthesize vMax;
// This is how a singlegton is created in Objective-C (or so I'm told)
static OpenCVWrapper *sharedInstance = nil;
+ (OpenCVWrapper *)sharedInstance {
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
return sharedInstance;
}
// Initialize the variables
// hue is from 0 to 180, saturation and value go from 0 to 255
-(id) init {
self = [super init];
self.hMin = 0;
self.sMin = 0;
self.vMin = 0;
self.hMax = 180;
self.sMax = 255;
self.vMax = 255;
return self;
}
然后我有导入 .h 文件的桥接头,编译器识别 OpenCVWrapper.sharedInstance,但如果我尝试获取或设置 sharedInstance.hMin,它会发现意外的 nil 并崩溃。
任何指针将不胜感激!
【问题讨论】:
-
CvVideoCamera 和 VideoHandler 是什么?它们是 Objective-C 对象吗?
-
查看您的代码 sn-ps,
OpenCVWrapper.sharedInstance.hMin甚至不应该编译。还有sharedInstance属性吗?不管怎样,试试OpenCVWrapper.sharedInstance().hMin。注意括号。 -
另外,似乎有更好的方法来设置单例,请参阅:stackoverflow.com/questions/7568935/…
-
@Omniprog 感谢您的信息。我将更新我的单例设置方式以匹配它。
-
@Karim CvVideoCamera 是一个 C++ 类,它是 OpenCV 的一部分。 VideoHandler 是一个 Objective-C 对象,它只是设置为 CvVideoCamera 的委托,并包含一些在帧渲染之前调用的方法。
标签: c++ ios objective-c swift opencv