Reputation: 1377
Hey guys at Stackoverflow!
I need your help. I am looking for a way to call my method only once after the application has launched and "save" the state of the color of the UIView. At first I will show you my code, that I can explain it in a better way:
-(void)viewWillAppear:(BOOL)animated {
NSArray *colors = [NSArray arrayWithObjects:[UIColor myWhiteColor],[UIColor myBlueColor],[UIColor myCyanColor],[UIColor myGreenColor],[UIColor myOrangeColor],[UIColor myPurpleColor],[UIColor myRedColor],[UIColor myViolettColor],[UIColor myYellowColor], nil]; NSInteger randomIndex = random() % [colors count]; colorTransparentView.backgroundColor = [colors objectAtIndex:randomIndex]; colorTransparentView.opaque = NO; colorTransparentView.alpha = 1.0;
}
Now I explain you my issue. As you can see, the code above changes the color of the UIView, every time the "viewWillAppear" method was called. The code randomly changes the color of the UIView(in the .xib) which is linked with an IBOulet to the header file. The problem is that every time I get back to the view I will get a different color.
However, I want to set the random color of the UIView
only once the application started. This color should stay until the application was closed from the Multitasking. I can't see any way to solve this. I tried to call the code in the applicationDidFinishedLaunchingWithOptions
method, but I wasn't succsessful.
Also I tried the dispatch_once
method to call it only once, but as you may think of the color was never called again, so the view got no color the second time loaded.
I really would appreceate if you could help me with this.
Thanks in Advance,
Noah
EDIT:
My header:
@interface ViewController : UIViewController {
IBOutlet UIView *colorTransparentView;
}
@end
Upvotes: 1
Views: 351
Reputation: 3154
Use dispatch_once. You can read up on singleton approaches in general, but this is the recommended approach.
Upvotes: 0
Reputation: 24195
What about using a static variable? initialise it with 0 and after changing color in your view will appear. set it to 1 and keep checking it.
int static colortaken = 0;
int static colorindex;
- (void)viewWillAppear:(BOOL)animated
{
NSArray *colors = [NSArray arrayWithObjects:[UIColor myWhiteColor],[UIColor myBlueColor],[UIColor myCyanColor],[UIColor myGreenColor],[UIColor myOrangeColor],[UIColor myPurpleColor],[UIColor myRedColor],[UIColor myViolettColor],[UIColor myYellowColor], nil];
if (colortaken == 0)
{
NSInteger randomIndex = random() % [colors count];
colorindex = randomIndex;
colorTransparentView.backgroundColor = [colors objectAtIndex:randomIndex];
colorTransparentView.opaque = NO;
colorTransparentView.alpha = 1.0;
}
else
{
// do nothin
colorTransparentView.backgroundColor = [colors objectAtIndex:colorindex];
colorTransparentView.opaque = NO;
colorTransparentView.alpha = 1.0;
}
// at end
colortaken = 1;
}
Upvotes: 3