I have MeetingUser C++ class; new_meetingUser is its object.
I want to add it to the NSMutableArray meetingUsersList, which I did using NSValue. However, I can't make out how to handle the memory of the object and the ownership of NSMutableArray.
MeetingUser *new_meetingUser = new MeetingUser(userName, dispName );
[meetingUsersList addObject:[NSValue valueWithPointer:new_meetingUser]];
You can add the C++ object to the array like that, but the array will not take ownership of the object. You will have to ensure that the object is not deleted while it's in the array, otherwise it will become a dangling pointer. Then you have to delete the object manually later, when you know it is safe to do so.
If you want the array to take ownership of the object, then you will have to use a CFMutableArray
. CFMutableArray
allows you to specify functions that called when objects are removed from the array, or when the array is deallocated. In your case, you want to set the CFMutableArray
to call delete
on the objects.
Essentially, you can't. C++ objects and Objective-C objects are totally different things, despite both being called "objects." NSArray can only hold Objective-C objects. It can't hold primitives, structs, C++ objects or anything else that is not an Objective-C object. The best workaround is to create an Objective-C class that wraps your C++ class and store that in the array.
One approach would be to write a small ObjC class to wrap your C++ object. This can be as simple or as complex as you want -- the only major thing it needs to do is store the C++ object in a field, and delete
it in dealloc
.
Similar problem I had
Create Objective C Wrapper class MeshHolder.hh
#import <Foundation/Foundation.h>
#include "Sculpt.h"
NS_ASSUME_NONNULL_BEGIN
@interface MeshHolder : NSObject
-(void) setupMesh:(Mesh_CPP *)mesh;
-(Mesh_CPP *)getMesh;
@end
NS_ASSUME_NONNULL_END
and.MM file
#import "MeshHolder.hh"
@implementation MeshHolder
Mesh_CPP * meshTEMP_;
-(void) setupMesh:(Mesh_CPP *)mesh {
meshTEMP_ = mesh;
}
-(Mesh_CPP *)getMesh {
return meshTEMP_;
}
@end
How to use it
@property(strong,nonatomic) NSMutableArray<MeshHolder*> *arrMeshes;
MeshHolder *meshH = [MeshHolder new];
[meshH setupMesh:meshTemp];
[_arrMeshes addObject:meshH];
Hope it is helpful as a quick example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.