Retain a random number across different functions in Cocoa? - cocoa

I know how to do a global variable, but whenever I try to define a global variable with a random number function, xcode says "initializer element is not constant." The compiler doesn't want to make a variable from a random number because the random number function is not constant.
How do I generate a random number and then use that same value for more than one action? (For example, to define a color and then write that value to a label?)
Code:
#import "Slider_with_IBAppDelegate.h"
float * const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);
//^this is where I get the error: "initializer element is not constant"
#synthesize label
//write value to label
- (IBAction) doButton {
label.text = [NSString stringWithFormat:#"%f", hue];
}
//set background color
- (void)applicationDidBecomeActive:(UIApplication*)application
{
self.label5.backgroundColor = [UIColor colorWithHue:hue
saturation:1.0
brightness:1.0
alpha:1.0];
}
----edit------
Thanks for the suggestions. It still doesn't work for me, though, what am I doing wrong?
New code:
#import "Slider_with_IBAppDelegate.h"
float const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);
//^I still get the error: "initializer element is not constant."
#synthesize label
//write value to label
- (IBAction) doButton {
label.text = [NSString stringWithFormat:#"%f", hue];
}
//^this is where I get the error "'hue' undeclared (first use of this function)"
//set background color
- (void)applicationDidBecomeActive:(UIApplication*)application
{
hue = ((arc4random() % ((unsigned)1000 + 1))/1000.0);
/*here I get the error "assignment of read-only variable 'hue.'"
If I insert "float" just before hue, I do not get this error,
but it still won't compile because of the error above.*/
self.label5.backgroundColor = [UIColor colorWithHue:hue
saturation:1.0
brightness:1.0
alpha:1.0];
}

Make it non-const and initialize it in applicationDidBecomeActive. Is there a reason it must be constant?

I know how to do a global variable, but whenever I try to define a global variable with a random number function, xcode says "incompatible types in initialization."
float * const hue = ((arc4random() % ((unsigned)100 + 1))/100.0);
That's not a function; it's an expression. I'd be surprised if you're not also getting an error here, because you can't initialize a global variable with an expression that isn't constant. As alltom.com says, you need to assign to it from applicationDidBecomeActive:.
The warning is because you've given the variable a pointer type (float *), but you're not assigning a pointer to it. Cut out the asterisk, because you're not going to put a pointer in this variable.
Xcode doesn't want to make a variable from a random number because the random number function is not constant.
Xcode doesn't care one way or the other. It's just reporting the findings of the compiler. By default, the compiler for Objective-C is GCC, but Xcode supports other compilers (and Xcode does come with one other C/Objective-C compiler: LLVM-GCC).
… I couldn't call the same value for the label.
You're not showing a label here, and you can't call a value. You can only call a function, and you don't have one in the code shown.
It gave me the error "function undefined: first use of this function" in doButton even though it was defined in applicationDidBecomeActive.
No, it wasn't. Assigning to a variable does not create a function.

In case anyone is wondering, I finally found a way to do this effectively. (I am sure this is what alltom was saying, I was just too dumb to understand.)
I declared a float and a seed in my .h file:
- (float)generate:(id)sender;
- (void)seed;
And in the implementation file, I defined the float as a random number, and I used srandom() as a random seed generator.
- (float)generate:(id)sender
{
//Generate a number between 1 and 100 inclusive
int generated;
generated = (random() % 100) + 1;
return(generated);
}
- (void)seed {
srandom(time(NULL));
}
Then anywhere I wanted to retain a random number, I used
srandom(time(NULL));
generated1 = ((random() % 100) + 1)/100.0;
to initiate the number, and from there I was able to use generated1, generated2, hue, etc. as variables in any function I wanted (and I made sure to declare these variables as floats at the top of the file).

Related

How do I convert this piece of code in c# to make it work in c++?

my aim is to capture the screen of a windows form using c++/cli. Below is the code to capture the window, however, it is in C#. What changes do I have to make to the code for it to work in c++?
Graphics myGraphics = this.CreateGraphics();
Size s = this.Size;
memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
What I've tried:
I've tried using the code below in c++, however, I get errors for the part in ** **.
The error says expected a ; after Size i.e. Size; s = this->Size; which does not make sense to me
Graphics^ myGraphics = this->CreateGraphics();
Size **s** = this->Size;
memoryImage = gcnew Bitmap(**s**->Width, s->Height, myGraphics);
Graphics^ memoryGraphics = Graphics::FromImage(memoryImage);
memoryGraphics->CopyFromScreen(this->Location.X, this->Location.Y, 0, 0, s);
Your code looks mostly correct.
I think that Size s is getting confused because Size is both the name of a type, and the name of a property on this object. It thinks you're trying to retrieve the Size property and throw away the result. To fix this, use the full name of the type for the declaration: System.Drawing.Size s = this->Size;. (You could also use auto, or remove the local variable entirely and just call this->Size several times.)
System.Drawing.Size is a value struct, not a ref class. It's a value type, not a reference type, so you need to do s.Width and s.Height.
This is similar to Location: Location returns a Point, which is a value type, and you're already doing Location.X, not Location->X.

Implicit conversion of 'int; to 'UIImage*' is disallowed with ARC

-(void)placeHole {
randomBlackHole = arc4random() %410;
randomBlackHole = randomBlackHole -10;
blackHole = randomBlackHole;
}
randomBlackHole is an integer and blackHole is an image within a button.
Yes, exactly. Implicit conversion of int to UIImage* is not allowed. Not with ARC, not without ARC. Not in C, C++, Objective-C, Java, or most other languages. What would it do? Do you think it should turn a number into an image?
BTW. It is highly recommended to start instance variables with an underscore character, so there is a clear distinction between using properties and using instance variables.

adding numbers in uitextfield to update uilabel

I have code with several uitextfields that will be used to input numbers, and I want to add these numbers together to update a uilabel.
I can do all the updating and the labels and fields, but can't get the addition to work.
Just now I have:
label.text = (textfield1.text + textfield2.text);
I assume I need to convert these textfield inputs to an int, but not sure how to do that...
there is a couple of extra steps you have to do:
convert the string value of your text filed into numerical value
do the math there
and convert it back.
For example (i use float in my case, you can change that to whatever type you want):
float textField1Value = [textfield1.text floarValue];
float textField2Value = [textfield2.text floarValue];
label.text = [NSString stringWithFormat:#"%f", textField1Value + textField2Value];
Hope that helps.

How to have a method return a float with multiple parameters in xcode?

I know there have been questions asked on this topic but they all differ slightly
what I want is a simple method that you pass an x value a y value and a quadrant value and it returns angle so far I have...
-(float)getAngle: (float)x yvalue:(float)y Quadrant:(float) quadrant{
float angle=0.0;
if(quadrant==1){
}
NSLog(#"%f",x);
return angle;
}
im not concerned about calculations at this point. I just want to know how to properly declare this method, because it wont let me name the first parameter.
Your code, as is, would work fine. Suppose you have a method like what you posted:
-(float)getAngle: (float)x yvalue:(float)y Quadrant:(float) quadrant{
float angle=0.0;
if(quadrant==1){
}
NSLog(#"%f",x);
return angle;
}
You could call this within the current class, and receive the returned value, like so:
// sample values added
float result = [self getAngle:-1.0 yvalue:0.5 Quadrant:2.0];
NSLog(#"%f",result);

How do you debug syntax errors in a Core Image kernel?

When writing a new Core Image filter, you need to write the kernel in the Core Image Kernel Language which is a mildly mutate OpenGL Shader Language. You compile these at runtime with something like this…
NSString *myCode = ...
NSArray *kernels = [CIKernel kernelsWithString:myCode];
The problem is any syntax error and you just get back a nil instead of an array. The documented API does not suggest a mechanism to get diagnostic information.
If you work on your filter in Quartz Composer, as recommended in the Apple docs, you will notice that it can give you syntax error information. (This only works for simple filters.)
So, how do you get diagnostic information back for an bad kernel source file?
Update: Depending on circumstances, you may get formatted lines on your console. If you are so lucky then you needn't worry about this, just look for lines like:
8: error: in function kernel vec4 clipDetection (uniform in sampler, uniform in float)
8: error: unknown variable name: gratuitous
Of course if you still need to get hold of the information…
If you use introspection on the CIKernel class, you will find a kernelsWithString:messageLog: method. There is no public interface to it, but don't let that stop you…
NSString *myCode = ...
NSMutableArray *messageLog = [NSMutableArray array];
NSArray *kernels = [[CIKernel class] performSelector:#selector(kernelsWithString:messageLog:) withObject:myCode withObject:messageLog];
if ( messageLog.count > 0) NSLog(#"Error: %#", messageLog.description);
The messageLog argument wants to be a mutable array. In the event of errors, it will have some dictionaries put into it. The contents of these are documented nowhere visible on the internet, but they look something like this (in a case where I added "gratuitous error" to a kernel's source)…
2012-12-06 17:56:53.077 MyProgram[14334:303] Error: (
{
CIKernelMessageDescription = "kernel vec4 clipDetection (uniform in sampler, uniform in float)";
CIKernelMessageLineNumber = 8;
CIKernelMessageType = CIKernelMessageTypeFunctionName;
},
{
CIKernelMessageDescription = "unknown variable name: gratuitous";
CIKernelMessageLineNumber = 8;
CIKernelMessageType = CIKernelMessageTypeError;
}
)
As always, think twice or more about leaving this in shipping code. It is undocumented and Apple could do anything to it at any time. They might even, you know, document it.

Resources