Reputation: 535
Lets say I want a BOOL to indicate the status of something. Then I call a class method that uses a recursive function to construct a certain string. Is there anyway to keep this BOOL outside of the class method so that it's status can change outside of the recursion? I'm finding a hard to ask this question clearly but I'm hoping you guys know what I'm trying to ask :/
Upvotes: 2
Views: 177
Reputation: 104698
There are two primitive approaches:
1) Visible to multiple files:
MONGlobalBOOL.h
extern BOOL MONGlobalBOOL;
MONGlobalBOOL.m
BOOL MONGlobalBOOL = NO;
2) Visible to one file:
MONGlobalBOOL.m
static BOOL MONGlobalBOOL = NO;
You don't want this in your headers because that will just emit a copy of the variable for each translation.
In use:
+ (void)method
{
if (MONGlobalBOOL) {
...
}
}
Careful, global mutable data frequently decays to evil stuff. You can likely solve your exact problem by creating a local variable on the stack.
Upvotes: 2
Reputation: 2290
As far as language support goes, anything that can be done in C can be done in Objective C. So you probably just want to use a static variable:
static BOOL globalFlag
Of course, if you only want to reference the variable within the recursive method, as in you want to send a flag to a calling method from a deeper recursion of the method, then you may do better passing the variable by reference:
- (void)someMethodWithRecursionFlag:(BOOL *)recursionFlag;
and then setting it by reference when needed:
*recursionFlag = YES;
and reading it when you're interested in it:
[self someMethodWithRecursionFlag:recursionFlag];
if (*recursionFlag)
[self doSomethingInteresting];
Upvotes: 1