Question

I want to check if a variable name is already defined. I don't care if it is equal to nil or not. I would use this in a macro that defines a variable if it is not yet defined. But if it is defined, the macro would just set the variable rather than redefining it (which actually prevents the compiler from building).

#define newAnimation()\
if (/* variableName is being used */) {\
    anim = [CABasicAnimation animation];\
} else {\
    CABasicAnimation* anim = [CABasicAnimation animation];\
}

I would then use the macro like so.

newAnimation();
anim.keyPath = @"position.x";
anim.toValue = @10;
[self.namedSubview addAnimation:anim forKey:nil];

newAnimation();
anim.keyPath = @"position.y";
anim.toValue = @50;
[self.otherSubview addAnimation:anim forKey:nil];

Note: The part with the macro is just my use case for this question. Your answer should work within a method.

Was it helpful?

Solution

It sounds like you just need a new inner scope from which you can declare non-conflicting identifiers. This is why it's always a good idea to wrap your identifier-declaring macros in a single do-while block, or simply a block. For example, you can change your macro to accept a code block and still keep consecutive invocations from conflicting with each other:

#define CFICreateAnimationInScope(BLOCK) { \
CABasicAnimation* anim = [CABasicAnimation animation]; \
BLOCK \
} \

void f() {
    CFICreateAnimationInScope({
        anim.keyPath = @"position.x";
        anim.toValue = @10;
    });

    CFICreateAnimationInScope({
        anim.keyPath = @"position.y";
        anim.toValue = @50;
    });
}

Beyond that, there's actually using a function-like macro (you seem to be confusing macros and C functions from the looks of that pair of empty parens) combined with the scoping changes above to make little animation factories.

OTHER TIPS

The preprocessor doesn't have information about variables and their names. Outside of its own limited control syntax, it is purely replacement of one bit of text with another, which is then passed on to the ObjC parser.

You can't fill in /* variableName is being used */ with anything to get the effect you're describing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top