Converting C std vectorEnum to an Objective-C Array
suggest changeMany C++ libraries use enums and return or receive data in vectors of enums. C enums are not Objective-C objects, so Objective-C collections cannot store them directly. The example wraps each value in an object and stores those objects in a generic NSArray. The collection’s element type is explicit, and there is no raw C array to free.
Here is the C enum & Objective-C equivalent object:
typedef enum
{
Error0 = 0,
Error1 = 1,
Error2 = 2
} MyError;
@interface ErrorEnumObj : NSObject
@property (nonatomic) int intValue;
+ (instancetype) objWithEnum:(MyError) myError;
- (MyError) getEnumValue;
@end
@implementation ErrorEnumObj
+ (instancetype) objWithEnum:(MyError) error
{
ErrorEnumObj * obj = [ErrorEnumObj new];
obj.intValue = (int)error;
return obj;
}
- (MyError) getEnumValue
{
return (MyError)self.intValue;
}
@end
And here is a possible use of it in Objective-C++ (the resulting NSArray can be used in Objective-C only files as no C++ is used).
class ListenerImpl : public Listener
{
public:
ListenerImpl(Listener* listener) : _listener(listener) {}
void onError(std::vector<MyError> errors) override
{
NSMutableArray<ErrorEnumObj *> * array = [NSMutableArray<ErrorEnumObj *> new];
for (auto&& myError : errors)
{
[array addObject:[ErrorEnumObj objWithEnum:myError]];
}
[_listener onError:array];
}
private:
Listener* _listener;
};
If this kind of solution is to be used on multiple enums, the creation of the EnumObj (declaration & implementation) can be done using a macro (to create a template like solution).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents