Semantic Issue: Comparison between pointer and integer - ios

I have researched online and couldn't find an answer. On Xcode 6 I have a error:
Semantic issue: Comparison between pointer and integer ('UILabel*' and 'int')
The code is (ViewController.m):
-(void)enemyMovement {
enemyShip.center = CGPointMake(enemyShip.center.x, enemyShip.center.y + 2);
if (CGRectIntersectsRect(enemyShip.frame, mothersShip.frame)) {
lives = lives - 1;
liveString = [NSString stringWithFormat:#"LIVES: %i", lives];
livesLabel.text = liveString;
//Stop enemy moving
[enemyMovementTimer invalidate];
if (livesLabel > 0) {
[self positionEnemy];
}
if ((livesLabel = 0)) {
[self gameOver];
}
}
}
-(void)gameOver {
[enemyMovementTimer invalidate];
[missleMovementTimer invalidate];
[self performSelector:#selector(replayGame) withObject:nil afterDelay:3];
}
- (void)replayGame {
score = 0;
lives = 3;
scoreString = [NSString stringWithFormat:#"SCORE: 0"];
liveString = [NSString stringWithFormat:#"LIVES: 3"];
scoreLabel.text = scoreString;
livesLabel.text = liveString;
startButton.hidden = YES;
friendlyShip.hidden = NO;
enemyShip.hidden = NO;
mothersShip.hidden = NO;
scoreLabel.hidden = NO;
livesLabel.hidden = NO;
[self positionEnemy];
}
The error occurs when integer is '1' but when integer is '0' the error doesn't occur and the lives goes into negative numbers, but the command doesn't occur for either number. The command is to revert back to the start of the game. I Think the problem is something to do with the way that the lives label is set out, I also think it might be something about the '=='. But i am not sure completely I have tried to solve this problem, but I have been unsuccessful, several times. I hope you can help me.
Thank You in advance

livesLabel > 0 is comparing the memory address of the livesLabel object to the number 0. What you want is to compare 0 to the text that the label shows. The comparison would look like this: [livesLabel.text intValue] > 0

You're comparing a label to a number. You might need to relearn some fundamental programming concepts, and I can't help you there, but a UILabel has a text property which can be parsed into an int with intValue.
if (livesLabel > 0) {
[self positionEnemy];
}
if ((livesLabel = 0)) {
[self gameOver];
}
I can't even tell what you're trying to achieve, you should compare lives instead, not the label to a number, its like trying to compare a sticker with a number, it makes absolutely no sense.

Related

How to limit characters and stop calculation in Calculator Screen

I'm using some calculator methods for my Login Screen.
Such as:
- (IBAction)numberPressed:(id)sender
{
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [[NSString alloc]initWithFormat:#"%2.f", currentNumber];
}
and
- (IBAction)C:(id)sender
{
[self setCurrentNumber:0];
calculatorScreen.text = #"Enter Password";
}
I am stuck with two things:
I need to limit the number of characters in the calculatorScreen.text to 7 characters.
I need to stop the number from multiplying after 8 entries.
I'm not sure what the reasoning is exactly, but after 8 button-presses the numbers start to multiply (change from original button number)
Have been looking around and trying different things and can't figure it out.
Thanks in advance.
To limit characters to 7:
- (IBAction)numberPressed:(id)sender
{
currentNumber = currentNumber *10 + (float)[sender tag];
if ([calculatorScreen.text length] == 7)
{
return;
}
else {
calculatorScreen.text = [[NSString alloc]initWithFormat:#"%2.f", currentNumber];
self.calculatorString = calculatorScreen.text;
}
}
Still not sure on how to fix the 'multiply' issue. If a user has a password over 8 characters, it's going to be a problem. But for now, I will set it to 7 characters to prevent it.

Clearing/Resetting all string and variables

I have a routine in xcode that calls a function and spits out a result to a UITextView element on an iPhone app.
Before the routine is started I want to reset all NSString objects/values and any variables that I used to calculate the result. Is there a quick way to do this?
So far no matter what I retype in the UITextField it just gets ignored after the initial calculation.
Code for the solve button :-
- (IBAction)Solve:(id)sender {
//
// Reset strings and variable code here
//
[_Number1 resignFirstResponder];
[_Number2 resignFirstResponder];
[_Number3 resignFirstResponder];
[_Number4 resignFirstResponder];
[_Number5 resignFirstResponder];
[_Number6 resignFirstResponder];
[_TargetNum resignFirstResponder];
// Dismiss Keyboard
int numb1,numb2,numb3,numb4,numb5,numb6,numTar;
numb1 = [self.Number1.text intValue];
numb2 = [self.Number2.text intValue];
numb3 = [self.Number3.text intValue];
numb4 = [self.Number4.text intValue];
numb5 = [self.Number5.text intValue];
numb6 = [self.Number6.text intValue];
numTar = [self.TargetNum.text intValue];
mainLoopOne(numb1,numb2,numb3,numb4,numb5,numb6,numTar);
// Start calculation with field values
readAnswers = #"Please read answers bottom-up.\n";
cantCalc = NULL;
finalResult = #"";
if (numb1 != 0) {
int ii;
for(ii = 0; ii < 6 ; ii++) {
if (allAnswers[ii] != NULL) {
finalResult = [finalResult stringByAppendingFormat:#"%#", allAnswers[ii]];
}
}
if (finalResult == NULL) {
cantCalc = #"Unfortunately, that doesn't seem to be possible, as there was no answer calculated.\n";
readAnswers = #"";
}
CompileText = [NSString stringWithFormat:#"%#\n%#\nfrom %d combination tries.", readAnswers, finalResult, countCombi];
[self.TextWin setText:CompileText];
}
countCombi = 0;
}
#end
Most of the strings and variables are set just under the #import "ViewController.h" so they are global :-
NSString *readAnswers;
NSString *cantCalc;
NSString *finalResult;
NSString *allAnswers[10];
NSString *CompileText;
NSString *readAnswers;
NSString *finalResult;
#define DIV 0
#define MUL 1
#define ADD 2
#define SUB 3
int n1,n2,n3,n4,n5,n6;
int answer_counter = 0;
int tar2 = 0;
int number[6];
int target = 0;
int used[6];
int countCombi;
Thanks.
Create a reset method that alloc inits every string in your view controller again. You can set the textview's text to "".
In theory you could write a helper class that you pass in an object (your view controller) and it uses introspection to reset everything that is a string or whatever you want. This is a good approach for modularity and reusability, however it requires knowledge of c, and introspection.
Yes whatever williams say thats correct. Implement like below:
-(IBAction)doClear:sender
{
[Yourtextview setString];
}

Pause and stop a method

I am making a stopwatch, but I only have the start button working. When the start button is pressed it enters a loop:
- (void)stopwatch
{
NSInteger hourInt = [hourLabel.text intValue];
NSInteger minuteInt = [minuteLabel.text intValue];
NSInteger secondInt = [secondLabel.text intValue];
if (secondInt == 59) {
secondInt = 0;
if (minuteInt == 59) {
minuteInt = 0;
if (hourInt == 23) {
hourInt = 0;
} else {
hourInt += 1;
}
} else {
minuteInt += 1;
}
} else {
secondInt += 1;
}
NSString *hourString = [NSString stringWithFormat:#"%02d", hourInt];
NSString *minuteString = [NSString stringWithFormat:#"%02d", minuteInt];
NSString *secondString = [NSString stringWithFormat:#"%02d", secondInt];
hourLabel.text = hourString;
minuteLabel.text = minuteString;
secondLabel.text = secondString;
CGRect hourFrame = self->hourBar.frame;
CGRect minuteFrame = self->minuteBar.frame;
CGRect secondFrame = self->secondBar.frame;
if ((NSInteger)hourFrame.size.height != hourInt) { // check if we need to modify
hourFrame.origin.y -= ((hourInt * 10.0) - hourFrame.size.height);
hourFrame.size.height = (hourInt * 10.0);
self->hourBar.frame = hourFrame;
}
if ((NSInteger)minuteFrame.size.height != minuteInt) { // check if we need to modify
minuteFrame.origin.y -= ((minuteInt * 4.0) - minuteFrame.size.height);
minuteFrame.size.height = (minuteInt * 4.0);
self->minuteBar.frame = minuteFrame;
}
if ((NSInteger)secondFrame.size.height != secondInt) { // check if we need to modify
secondFrame.origin.y -= ((secondInt * 4.0) - secondFrame.size.height);
secondFrame.size.height = (secondInt * 4.0);
self->secondBar.frame = secondFrame;
}
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(stopwatch) userInfo:nil repeats:NO];
}
When the stop button is pressed, I want this loop to be paused so that when the user presses start, it resumes the stopwatch.
When the reset button is pressed, I want the loop to stop and reset back to 0.
If you could make your answer as simple as possible, that would be really great because I'm only a beginner!
You should take the timer out of your 'loop' method and make it repeating. It should be the thing that is driving the stopwatch, not that fact that you have started your 'loop'. Then, you can stop the timer when you need to and restart it later. You can also google to find out the correct way to pause the timer (you need to change the timer to start at a specified fire date to be 100% accurate, but just knowing how many seconds are left may be enough for your case).
Based on your previous question it sounds like you have moved your timer outside of your stopwatch method. Remember, timers and loops are two very different things.
You can stop an NSTimer by calling invalidate on it. Please read Apple's documentation for more details.
One way that might not be completely thread safe but I just tested it and it works is to have a variable that is set to true when you click start and false when you click stop.
For example, in my .h, I added #property (nonatomic) BOOL go;, then as the first line of the method you provided, add an if check that looks like this:
- (void)stopwatch {
if (!self.go) return;
//..do the rest of your stopwatch code
//the timer call
}
then my start and stop button calls look like:
- (void)start {
if (!self.go) { // Do not call the stopwatch method again if it is already going.
self.go = YES;
[self stopwatch];
}
}
- (void)stop {
self.go = NO;
}
Loop is the wrong construct for this type of operation. For better control, use NSTimer.
A relevant example can be found here.
EDIT:
My above answer was based on prior version of your question.
So yes, the NSTimer should be the controlling thing for your loop, not part of the loop.
General implementation:
Start should only mark timer starting. Also note the current time from system clock. (this is optional though)
Timer function should change value of the time variable, and compare it against the stopwatch set value. If time elapsed == set value, stop the timer using invalidate.
Stop should interrupt the timer and stop it, and also the elapsed time value should be set to 0. Time Variable should be reset too, if you do not want to reuse this same time value again.

scientific calculator tutorial for iPhone/ipad

i have been looking for a tutorial for a scientific calculator one the web but i could not find anything. my aim is to learn how to write a calculator app similar to the one in iPhone. does any know of any tutorials that can help me learn how to add scientific functions to a calculator app. keep in mind that i have tried the various versions of the basic calculator and have been through a few of those tutorials and just want to learn and may use the methods to add scientific functions such as rad, sin, cos and some other stuff in the app. i will be great full for any help i can get.
AP
Edit:
since there are no real material on how to build a scientific calculator out there( at least i haven't found anything specific yet) here is the run down of how to build one.
first create a NSObject class to hold your operation methods. ( this is optional, you can set it on top of your getter (.m) file if you like.) call it whatever you want. then declare the following the the header file.
{
double operand;
double savedNumber;
NSString *waitingOperation;
double waitingOperand;
}
- (void)setOperand:(double)aDouble;
- (double)performOperation:(NSString *)operation;
- (void)performWaitingOperation;
#end
then in the .m file of your NSObject class declare the methods that operates your functions. something like the following:
-(void)setOperand:(double)num
{
operand=num;
}
-(double)performOperation:(NSString *)operation
{
if([operation isEqual:#"sqrt"]){
operand = sqrt(operand);
}else if ([operation isEqual:#"1/x"]){
if(operand)
operand = 1 / operand;
}else if ([operation isEqual:#"2/x"]){
if(operand)
operand = 2 / operand;
}else if ([operation isEqual:#"3/x"]){
if(operand)
operand = 3 / operand;
}else if ([operation isEqual:#"+/-"]){
if(operand)
operand = (-1) * operand;
}else if ([operation isEqual:#"sin"]){
operand = sin(operand);
}else if ([operation isEqual:#"sinh"]){//you can add more scientific functions in the same way to this list.
operand = sinh(operand);
}else if ([operation isEqual:#"cos"]){
operand = cos(operand);
}else if ([operation isEqual:#"cosh"]){
operand = cosh(operand);
}else if ([operation isEqual:#"tan"]){
operand = tan(operand);
}else if ([operation isEqual:#"tanh"]){
operand = tanh(operand);
}else if ([operation isEqual:#"M"]){
savedNumber = operand;
}else if ([operation isEqual:#"M+"] ){
savedNumber += operand;
}else if ([operation isEqual:#"M-"] ){
savedNumber -= operand;
}else if ([operation isEqual:#"Recall"]){
[self setOperand:savedNumber];
}else if ([operation isEqual:#"C"]){
savedNumber = 0;
operand = 0;
waitingOperand = 0;
savedNumber= 0;
}else {
[self performWaitingOperation];
waitingOperation = operation;
waitingOperand = operand;
}
return operand;
}
- (void) performWaitingOperation
{
if([#"+" isEqual:waitingOperation]){
operand = waitingOperand + operand ;
} else if([#"-" isEqual:waitingOperation]){
operand = waitingOperand - operand ;
}else if([#"X" isEqual:waitingOperation]){
operand = waitingOperand * operand ;
}else if([#"/" isEqual:waitingOperation]){
if(operand)
operand = waitingOperand / operand ;
}
}
now in the view controller that you are trying to display the calculator you need to access all of these functions and display them in your outlets, such as buttons and text field and so on. here is the .h file
IBOutlet UILabel *display;
SCalcAI *ai;
BOOL userIsInTheMiddleOfTypingNumber;
}
- (IBAction) digitPressed: (UIButton *)sender;
- (IBAction) operationPressed: (UIButton *) sender;
rememebr to import your NSObject class header on top of this file otherwise you get an error. then in the .m file you need to declare these functions.
-(NameofyourNSOBjectClass *) ai
{
if(!ai)
{
ai = [[SCalcAI alloc] init];
}
return ai;
}
- (IBAction) digitPressed: (UIButton *)sender
{
NSString *digit = [[sender titleLabel] text];
if(userIsInTheMiddleOfTypingNumber){
[display setText:[[display text] stringByAppendingString:digit]];
} else{
[display setText:digit];
userIsInTheMiddleOfTypingNumber = YES;
}
}
- (IBAction) operationPressed: (UIButton *) sender
{
if(userIsInTheMiddleOfTypingNumber){
[[self ai] setOperand:[[display text] doubleValue]];
userIsInTheMiddleOfTypingNumber = NO;
}
NSString *operation = [[sender titleLabel] text];
double result = [[self ai] performOperation:operation];
[display setText:[NSString stringWithFormat:#"%g", result]];
}
then hook up all the buttons to the operations they need to be connected in the storyboard or xib. thats that. the above is the skeleton version of the whole thing but I'm sure you can build on that. if you need help send me message.
The Standford iOS programming class cs193p has an example of building a simple calculator. Might be a good place to start. Great course, great videos. Paul Hagarty is a very good instructor. The scientific functions would not be hard to add once you have the core done.
Two resources:
http://www.tusharsharma.in/project/open-source/mathematical-calculator-iphone4/
http://emplementation.blogspot.com/2010/11/ios-development-tutorials-on-itune-u.html

Decimal place not displaying correctly in Xcode?

I got the decimal working now but for some reason its displaying backwards. It's probably my lack of math skills but here is the code:
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = (float)[sender tag] + currentNumber /10;
priceOne.text = [NSString stringWithFormat:#"%.2f",currentNumber];
}
Now when I type on my custom keyboard in this order: 5-2-1, it displays the number backwards: 1.25. I want it to display 5.21. Any ideas?
In your #interface add a new instance variable
float currentMultiplier;
Set it in your (re-)initialisation routine, so:
currentMultiplier = 1.0;
and recode the routine you mention in the question as:
-(IBAction)buttonDigitPressed:(id)sender
{
currentNumber += (float)[sender tag]*currentMultiplier;
currentMultiplier *= 0.1;
priceOne.text = [NSString stringWithFormat:#"%.2f",currentNumber];
}
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = currentNumber*10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"%2f",currentNumber];
}

Resources