I have tried so many combination's of code I don't have a sample to show.
I have a Objective C view controller, and in the interface I declare a C++ class that contains the preferences of what the user wants to have. I do my @property command in the header and @synthesize command at the top of the .mm file.
Then I use the class in the loadView method and it initialises, which is a good thing and I load all 开发者_运维知识库the preferences into the class exactly how I want them to go, which is all fine.
Then down in the other methods such as numberOfSectionsInTableView and numberOfRowsInSection, etc, I go to use the class to retrieve the values, and this goes wrong.
The class initialises every time I go to use it. So when want to know how many groups in the preference file, the C++ method I called countGroup, it just reinitialises everything and there is no longer any data in my C++ class.
What I think, is that the @property command has generated the getters and setters in a way that specifically reinitialises classes. This is just a guess but if I'm right how do I over write them or is there some other way of using my C++ class globally through out my view controller.
Note: the C++ class doesn't work if it's referenced as a pointer because it's got loads of nested vectors and stuff, the compiler just throws a wobbly at that.
I had a similar story to you where I tried to use boost shared pointers and weird and crazy stuff kept happening.
Objective-C++ just doesn't work by the same rules as C++. The memory scope rules of C++ classes are not covered by Obj-C++. Things like smart pointers and vectors just won't work properly in Obj-C++.
The way that I got around it was to write a very simple container class:
class MyContainerClass
{
public:
boost::shared_ptr<MyClass> mySharedPointer;
/// etc
};
Then in my Obj-C++ code I'd allocate/free the above the Obj-C++ way:
- (id)init
{
if (self = [super init])
{
myContainer = new MyContainerClass();
// etc
}
return self;
}
and
- (void)dealloc
{
// etc
delete myContainer;
[super dealloc];
}
Then I'd have an accessor like:
- (boost::shared_ptr<MyClass>)mySharedPointer
{
return myContainer->mySharedPointer;
}
It's an ugly approach but it's the only way I could figure out how to get around this issue.
精彩评论