Updated
I'm trying to draw a random number and not repeat the previous number
NSArray *placement = #[#300,#400,#500,#600,#700];
float placement1 = [placement[arc4random_uniform(5)]floatValue];
float recentdraw;
if (placement1 == recentdraw) {
//float placement1 = [placement[arc4random_uniform(5)]floatValue];
}
else {
placement1 recentdraw;
// den vertikale placering af labelen randomizes nu ved hvert swipe
self.Label.frame = CGRectMake(30, placement1, 400, 500);
placement1 = recentdraw;
};
what I want to do here is under the 'if' part to set the code to repeat itself. I'm very new in coding, so I hope to avoid creating my own method/function - basically just make this as simple as possible
Couldn't find any thread that made me understand this
Use [placement[1] floatValue]. It will return float value of your NSNumber. #400 is the same as [NSNumber numberWithInt:400] and as CGRectMake takes only CGFloat's as parameters you need to convert NSNumber from the array to the float.
Related
How do I concatenate the int length to the string I'm trying to slap into that array so it is "C10" given length == 10, of course. I see #"%d", intVarName way of doing it used else where. In Java I would of done "C" + length;. I am using the replaceObjectAtIndex method to replace the empty string, "", that I have previously populated the MSMutableArray "board" with. I am getting an error though when I add the #"C%d", length part at the end of that method (second to last line, above i++).
As part of my homework I have to randomly place "Chutes" (represented by a string of format, "C'length_of_chute'", in this first assignment they will always be of length 10 so it will simply be "C10") onto a game board represented by an array.
-(void)makeChutes: (int) length {// ??Change input to Negative number, Nvm.
//??Make argument number of Chutes ??randomly?? across the board.
for(int i = 0; i < length;){
int random = arc4random_uniform(101);
if ([[board objectAtIndex:random] isEqual:#""]) {
//[board insertObject:#"C%d",length atIndex:random];
[board replaceObjectAtIndex:random withObject:#"C%d",length];
i++;
}
}
}
Please ignore the extra and junk code in there, I left it in for context.
In Objective-C the stringWithFormat method is used for formatting strings:
NSString *formattedString = [NSString stringWithFormat:#"C%d", length];
[someArray insertObject:formattedString];
It's often easier to create your formatted string on a line of its own in Objective-C, since as you can see the call can be fairly verbose!
I have two text fields that are for percentages to be entered in. If i put 20 in the first field I would like the second text field to be updated to 60. And later on if I changed the second one to say 30, I would like the first updated to 70.
For ease of showing what I mean, say I have two text fields _firstPercent and _secondPercent with associated labels _firstTotal and _secondTotal:
float firstPercent = [_firstPercent.text floatValue];
float firstAmount = (firstSalePercent / 100) * firstOrigonalAmount;
_firstTotal.text = [NSString stringWithFormat:#"%1.0f",firstAmount];
float secondPercent = [_secondPercent.text floatValue];
float secondAmount = (secondSalePercent / 100) * secondOrigonalAmount;
_secondTotal.text = [NSString stringWithFormat:#"%1.0f",secondAmount];
I really don't know how to handle this so I tried adding this below its respective code. It works for the first one, but not the second.
float percentToSecond = 100 - firstPercent;
_secondPercent.text = [NSString stringWithFormat:#"%1.0f", percentToSecond];
float percentToFirst = 100 - secondPercent;
_firstPercent.text = [NSString stringWithFormat:#"%1.0f", percentToFirst];
I have tried other solutions but don't know what to do.
I would just like someone to lead me in the right direction.
Thanks
How about using the delegate method controlTextDidEndEditing: to see what value was entered, and then set the value for the other text field. In the following code tf1 and tf2 are the IBOutlets for the two text fields.
-(void)controlTextDidEndEditing:(NSNotification *)obj {
float value = [[[obj.userInfo valueForKey:#"NSFieldEditor"] string] floatValue];
if (obj.object == self.tf1) {
self.tf2.stringValue = [NSString stringWithFormat:#"%1.0f",100. - value];
}else if (obj.object == self.tf2) {
self.tf1.stringValue = [NSString stringWithFormat:#"%1.0f",100. - value];
}
}
You'd have to do some more checking to make sure the user didn't enter a number greater than 100 or something not a number.
I am trying to add a positive/negative button onto a numerical input in a UItextfield, but I cannot get it to function properly. What I want it to do is just add or remove a negative sign from the front of the numerical input. I am able to do that, however I cannot find a method to maintain the original number of decimal places. This is what I have tried:
- (IBAction) negsign
{
float input = [userinput.text floatValue];
float result = ((input * (-1)));
negstring = [NSString stringWithFormat:
#"%f", result];
userinput.text = negstring;
}
With this I get just a string of zeros after, like -23.0000000. I've tried limiting the decimal places by changing to #"%.2f" but I dont want extra zeros for whole integers, or rounding more than 2 decimals places. I just want it to take something like 34.658939 or 23 and make it -34.658939 or -23. Does anyone have a method to do this?
What would work best in your case is the following code:
float input = [userinput.text floatValue];
float result = ((input * (-1)));
NSNumber *resultNum = [NSNumber numberWithFloat:result];
NSString *resultString = [resultObj stringValue];
userinput.text = resultString;
If you're trying to make the number negative instead of reversing the sign, it'd be better if you replace float result = ((input * (-1))); with float result = -ABS(input);
Really, the best way to handle this would be to never convert it from a string in the first place. Just replace the first character as needed like this:
- (IBAction) negsign
{
unichar firstCharacter = [userinput.text characterAtIndex:0];
if (firstCharacter == '-') {
// Change the first character to a + sign.
userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:#"+"];
} else if (firstCharacter == '+') {
// Change the first character to a - sign.
userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:#"-"];
} else {
// There is no sign so we assume that it is positive.
// Insert the - at the beginning.
userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 0)
withString:#"-"];
}
}
Im using core-plot for my graphing component of my iPhone app, and I have been using NSDecimal object a lot.
One of the lines of their code that I have seen is like this:
-(void)plotPoint:(NSDecimal *)plotPoint forPlotAreaViewPoint:(CGPoint)point
{
NSDecimal x;
//do some calculations on x
plotPoint[CPCoordinateX] = x;
}
Where, CPCoordinateX is deinfed as below:
typedef enum _CPCoordinate {
CPCoordinateX = 0, ///< X axis
CPCoordinateY = 1, ///< Y axis
CPCoordinateZ = 2 ///< Z axis
} CPCoordinate;
The line:
plotPoint[CPCoordinateX] = x;
is what I dont understand, how can a NSDecimal be assigned to like this?
In my code, Im trying to call this method, like so:
NSDecimal dec = CPDecimalFromInteger(0);
[plotSpace plotPoint:&dec forPlotAreaViewPoint:point];
NSDecimalNumber *newx = [[NSDecimalNumber alloc] initWithDecimal:dec];
NSDecimal x = dec[CPCoordinateX];
//NSLog(#"converted at: %#", newx);
but Im getting compile errors:
error: subscripted value is neither array nor pointer
Can someone please explain this to me?
plotPoint is a pointer and pointers can be indexed like arrays using the subscript operator:
int array[] = { 1, 2, 3 };
NSLog(#"x=%d, y=%d, z=%d", array[0], array[1], array[2]);
// prints "x=1, y=2, z=3"
int *pointer = array; // implicit conversion to pointer
NSLog(#"x=%d, y=%d, z=%d", pointer[0], pointer[1], pointer[2]);
// also prints "x=1, y=2, z=3"
You can also use those expressions for assignments:
array[0] = 4;
pointer[1] = 5;
But you can only use the subscript operator on arrays or pointers:
NSDecimal dec = CPDecimalFromInteger(0);
dec[0]; // illegal, dec is a single NSDecimal value, not pointer or array
To actually pass a point -plotPoint:forPlotArrayViewPoint: you need a C-style array or a dynamic array of 2 or 3 NSDecimals (according to what dimensions the method expects), e.g.:
NSDecimal decPoint[] = {
CPDecimalFromInteger(0),
CPDecimalFromInteger(0),
CPDecimalFromInteger(0)
};
[plotSpace plotPoint:decPoint forPlotAreaViewPoint:point];
On that array you can now also use the subscript operator:
NSDecimal x = decPoint[CPCoordinateX];
It's a C array.
I'm attempting to define an extremely simple utility method that will save me from having to use a calculator to define RGB values as percentages. When I look into Apple's sample code called "QuartzCache", in the DrawView.m file, line 96, I see this:
float whiteColor[4] = {1, 1, 1, 1};
However, when I attempt to created a method like the following, the compiler hates me. A half-hour of intensive Googling has not produced any help.
+(float[])percentagesRGBArray:(float[])rgbArray{
float red = rgbArray[0];
float green = rgbArray[1];
float blue = rgbArray[2];
float alpha = rgbArray[3];
red = red/255;
green = green/255;
blue = blue/255;
alpha = alpha;
float percentagesRGBArray[4] = {red, green, blue, alpha};
return percentagesRGBArray;
}
What is the proper way to define such a method? What am I doing wrong here?
Define a struct that contains all of the components, or wrap up each individual component in an NSNumber. Alternatively, use an NSColor instance to contain your colour components.
struct way:
typedef struct
{
float red;
float green;
float blue;
float alpha;
} MyColor;
- (MyColor) percentagesRGBArray:(MyColor) incoming
{
MyColor result;
result.red = incoming.red / 255;
result.green = incoming.green / 255;
result.blue = incoming.blue / 255;
result.alpha = incoming.alpha;
return result;
}
NSNumber way:
- (NSArray *) percentagesRGBArray:(float[]) rgbArray
{
NSNumber *red = [NSNumber numberWithFloat:rgbArray[0] / 255];
NSNumber *green = [NSNumber numberWithFloat:rgbArray[1] / 255];
NSNumber *blue = [NSNumber numberWithFloat:rgbArray[2] / 255];
NSNumber *alpha = [NSNumber numberWithFloat:rgbArray[3]];
return [NSArray arrayWithObjects:red, green, blue, alpha, nil];
}
NSColor way:
- (NSColor *) percentagesRGBArray:(float[]) rgbArray
{
CGFloat red = rgbArray[0] / 255;
CGFloat green = rgbArray[1] / 255;
CGFloat blue = rgbArray[2] / 255;
CGFloat alpha = rgbArray[3];
return [NSColor colorWithDeviceRed:red
green:green
blue:blue
alpha:alpha];
}
Normally, you would use Cocoa's NSColor class to handle this sort of thing, but it looks like you are doing something a little more low-level.
In that case, I would do the following:
typedef struct
{
float red;
float green;
float blue;
float alpha;
}
RGBAData;
RGBAData ConvertRGBAToPercentages(const RGBAData source)
{
RGBAData percentages;
percentages.red = source.red/255;
percentages.green = source.green/255;
percentages.blue = source.blue/255;
percentages.alpha = source.alpha/255;
return percentages;
}
To be used as follows:
RGBAData original = { 0xFF, 0xFF, 0x00, 0x80 }; // 50% transparent yellow
RGBAData percents = ConvertRGBAToPercentages(original);
Both e.James and dreamlax's answers give good approaches for doing this. But to answer what was wrong with your original code:
Basically, it has to do with how C arrays work. An array is essentially equivalent to a pointer to its first element. In fact, when you pass an array to a function, it decays into a pointer. You're still allowed to name the argument float myArray[4] (you have to declare the number of elements) just to make it clear that the pointer is supposed to be to an array of 4 elements — but you're still getting a pointer. Now consider the return value. What are you returning? We already established that you can't return an array by value, because it decays into a pointer. But even if you change the return type to be a pointer, it still won't work, because the array will have gone out of scope once the function returns. In order to return an array, you have to malloc the memory, and then you're responsible for freeing it later.
This is why you should avoid working with C arrays when at all possible. They're really low-level and fiddly. Even when you do use them, it's usually a good idea to hide them behind an API that takes care of the low-level details for you.
I think i'm late) but i have just found this thread.
the C way to do this is to create an array before invoking a function;
+(void) percentagesRGBArray:(float[])inArray toArray:(float*)outArray {
...
}
float array1[4];
float array2[4];
[MyClass percentagesRGBArray:array1 toArray:array2];