0

Is there a way to create a scoped variable/object with a constructor/destructor (on stack) in Objective-C or will I need to add C++ for this?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I was trying to avoid this for now (C++/.mm) but if that is the only option then I will do this
That's the only option you have to use C++ with Objective-C++. Not sure what you're trying to do here.
Want a scoped structure for logging entry and exit of methods
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.