Automatic variable in Objective-C
Is there a way to cre开发者_Go百科ate a scoped variable/object with a constructor/destructor (on stack) in Objective-C or will I need to add C++ for this?
You don't need to add C/C++ anywhere, since Objective-C is already C or C++.
You can use scoped variables in any message (function) you want:
-(void) myMessage
{
// default constructor will be called
MyCPPClass myCPPClassInstance; // scoped variable of type MyCPPClass class
myCPPClassInstance.Method(); // using MyCPPClassInstance
return;
// destructor will be called after returning
}
Do note that you will have to use a file name ending with .mm in order to use C++ in Objective-C. If you just need C, then you just variables as you would in any other C function.
Is there a way to create a scoped variable/object with a constructor/destructor (on stack) in Objective-C
No.
You can created scoped C variables on the stack (obviously!) but not Objective-C classes. The concept of constructor/destructor does not exist in Objective-C.
or will I need to add C++ for this?
Yes.
But it will only work with C++ objects. I suppose you could create a C++ class to wrap an Objective-C object that allocates the Objective-C object in its constructor and releases (note not deallocs) it in the destructor. However, if you do that you might as well autorelease as soon as you alloc.
精彩评论