Obj-C: ++variable is increasing by two instead of one - objective-c

I am writing a program that asks users yes/no questions to help them decide how to vote in an election. I have a variable representing the question number called questionnumber. Each time I go through the switch-break loop, I add 1 to the questionnumber variable so that the next question will be displayed.
This works fine for the first two questions. But then it skips the third question and moves on to the fourth. When I have more questions in the list, it skips every other question. Somewhere, for some reasons, the questionnumber variable is increasing when I don't want it to.
Please look at the code below and tell me what I'm doing wrong.
Thank you!
Eli
#import "MainView.h"
#import <Foundation/Foundation.h>
#implementation MainView
#synthesize Question;
#synthesize mispar;
int conservative = 0;
int liberal = 0;
int questionnumber = 1;
- (IBAction)agreebutton:(id)sender { ++liberal; }
- (IBAction)disagreebutton:(id)sender { ++conservative; }
- (IBAction)nextbutton:(id)sender
{
++questionnumber;
switch (questionnumber)
{
case 2: Question.text = #"Congress should ...."; break;
case 3: Question.text = #"It is not fair ..."; break;
case 4: Question.text = #"There are two ..."; break;
case 5: Question.text = #"Top quality h..."; break;
default: break;
}
}
#end

It's a bit hard to read, if you can copy it exactly how it is in the implementation file and use the code sample feature for posting code snippets.
To answer the previous question
number++;
That just adds 1 to the value.
number+=anotherNumber;
That will add anotherNumber to number, and is a quick way of saying
number = number + anotherNumber;
As for your code, is there a chance that the nextButton method is being called more then once?

does ++ automatically add 1 to the variable or does it add the variable + itsself
so if questionnumber = 1 then
does ++questionumber add questionnumber + questionnumber if so it will only work the 1st time and will skip 3 so when questionnumber is 2 you would be adding questionnumber + questionnumber which = 4
I would change to questionnumber = questionnumber + 1 or if the language supports it questionnumber += 1
Where do you set the increment seed for ++ i believe this functionality is typically used with a for loop.

Related

Reaching unexpected objc breakpoint with method __Block_byref_object_copy_

I'm using lldb to debug objc based service. several breakpoints (which is set
have been placed in the code, and I see that one of them is reached unexpectedly according to the stack trace.
The method encapsulating this breakpoint shouldn't have called but I still see it in stack trace (file1.mm:97) although it seems like the code isn't being execute there.
I suspect that objc internal method __Block_byref_object_copy_ is responsible for copying the block of code which involves both caller and callee methods (MyClass from the upper frame in the stack and the method in file1.mm:97).
While copying the debugger probably thinks that it reach this line for execution and stop there, where in fact it's only for copying the code block which involves those 2 methods.
Perhaps anybody can support this claim or provide additional explanation of why am I getting this breakpoint where it shouldn't occur ?
* frame #0: 0x0000000107e03ce0 MyLib`::__Block_byref_object_copy_((null)=0x00007fda19a86b30, (null)=0x00007ffeea7f3bd0) at file1.mm:97:27
frame #1: 0x00007fff7de6bb78 libsystem_blocks.dylib`_Block_object_assign + 325
frame #2: 0x0000000107dd960a MyLib`::__copy_helper_block_ea8_32r((null)=0x00007fda19a86540, (null)=0x00007ffeea7f3ba8) at file2.mm:47:55
frame #3: 0x00007fff7de6b9f3 libsystem_blocks.dylib`_Block_copy + 104
frame #4: 0x00007fff7c64e1e8 libobjc.A.dylib`objc_setProperty_atomic_copy + 53
frame #5: 0x00007fff5411d16b Foundation`-[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:] + 1885
frame #6: 0x00007fff54168508 Foundation`-[NSXPCConnection _sendSelector:withProxy:arg1:arg2:] + 125
frame #7: 0x00007fff54168485 Foundation`_NSXPCDistantObjectSimpleMessageSend2 + 46
frame #8: 0x0000000107e0520e MyLib`::-[MyClass func:withVar0:Var1:Var2:withError:](self=0x00007fda17c2cb50, _cmd="funcWithVar0:Var1:Var2:Var3:withError:", var0="aaa", var1=0x0000000000000000, var2="bbb", var3=0x00007fda17d41dd0, err=0x00007ffeea7f4258) at MyClass.mm:196:5
UPDATE:
thanks to the comments below, it happen that if I set breakpoint according to file and line, it gives me 3 locations (!?)
breakpoint set --file myfile.mm --line 97
now when I list my breakpoints, it give me 2 breakpoints that aren't related to the actual method which wraps the file, besides the expected breakpoint.
3.2: where = my class`::__Block_byref_object_copy_() + 16 at myfile:97:27, address = 0x0000000107e03ce0, unresolved, hit count = 0
3.3: where = myclass `::__Block_byref_object_dispose_() + 16 at myfile:97:27, address = 0x0000000107e03d40, unresolved, hit count = 0
Not really an answer, more an illustration ...
unsigned fn ( void )
{
return 3; // Set bp here and see what happens
}
int main(int argc, const char * argv[])
{
#autoreleasepool
{
// insert code here...
NSLog(#"Hello, World!");
unsigned int x = 0;
x = 1;
x = 2;
x = 3;
if ( x >= 0 )
{
switch ( 5 )
{
case 1 : x = 4; break;
case 2 : x = 4; break; // Set bp here - it will trigger!!!!
case 3 : x = 4; break;
case 4 : x = 4; break;
case 5 : x = 4; break; // Set bp here and see what happens
case 6 : x = 4; break;
case 7 : x = 4; break;
default : x = 4; break;
}
}
__block unsigned y;
void ( ^ b1 )( void ) = ^ {
y = fn();
};
void ( ^ b2 )( void ) = ^ {
b1();
};
if ( YES )
{
b2();
}
NSLog ( #"x = %u y = %u", x, y );
}
return 0;
}
Without going into too much detail, note that most of the code above will be optimised away. The compiler will optimise for loops and switches aggressively and will optimise superfluous assignments and checks (e.g. x >= 0 for unsigned x) away. Above even the blocks gets inlined and you end up with what appears to be very strange behaviour. I think the blocks here are relevant to your specific problem?
If you optimise then the first breakpoint indicated in the code does not get triggered as the blocks all get inlined (I think as I did not look at the disassembly). Likewise the third one does get triggered, but because of optimisation in the strangest of places. Really, a large part of the code gets reduced into a single assignment and the compiler does not really know where to stick it so when that bp is triggered it looks as if it is in the strangest and most disconnected place possible.
Finally, even the second (!!!) one will trigger. That code should never execute but since it all collapse due to optimisation you can even get it to trigger.
So I would not be too perplexed about what triggers your bp ...
I mean, above I just proved that 2 == 5 if I take the bp seriously. And that is not even variable but constant 2 == 5!!! Quite amusing ...

how do I make a limit in up counter?

I am new to Objective-C and I made an up counter. By tapping on a button it will increment by one and made another button to reset to 0 but the problem is I could not make is stop in a spacific number e.g I want it when it reaches 15 reset again to zero
-(IBAction)up:(id)sender{
numbercount = numbercount +1 ;
counterdisplay.text = [NSString stringWithFormat:#"%i" , numbercount];
}
-(IBAction)reset:(id)sender{
numbercount = 0 ;
counterdisplay.text = [NSString stringWithFormat:#"%i" , numbercount];
that is my project
Let's say the you have the value of your counter stored in a variable, say, counterValue.
Every time you add 1 to counterValue, simply check if the new value equals 15, and if it does, reset the value back to 0.
- (void)buttonTapped {
counterValue++;
if(counterValue == 15) {
counterValue = 0;
}
}
I can't give you a more specific example because you didn't share your current code, so hopefully this is enough to get you started in your own project.
Welcome to Stack Overflow!

variable for textfield Objective c [duplicate]

This question already has answers here:
Create multiple numbered variables based on a int
(2 answers)
Closed 8 years ago.
I'm using
for(int k=i;k<6;k++){
int q=k+1;
switch (q) {
case 1:
textbox1.hidden=YES;
break;
case 2:
textbox2.hidden=YES;
break;
case 3:
textbox3.hidden=YES;
break;
case 4:
textbox4.hidden=YES;
break;
case 5:
textbox5.hidden=YES;
break;
case 6:
textbox6.hidden=YES;
break;
default:
textbox1.hidden=NO;
break;
}
}
I was wondering if there isn't anyway to use make something like this:
[#"textbox%#.hidden] = YES
or something like that..
The second question
I have to do something likes this:
[textbox2 setKeyboardType:UIKeyboardTypeDecimalPad];
But since Im on a for .. I can't put textbox2 I need to put "textbox%#, i" So it can detect on which textbox it is analyzing any idea?
You cannot make the replacement you're asking about. It's probably possible to figure out some alternative using reflection but the resulting code will be much uglier than what you've already got. You could, however, take advantage of your q being 1-6 and use an array of text boxes:
id textboxes[] = {textbox1, textbox2, ... textbox6};
if ((q >= 1) && (q <= 6)) textboxes[q-1].hidden = YES;
else textbox1.hidden=NO;

'Expected expression' errors [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I'm getting Expected expression errors on the following code:
(void) for(t; t < kPlatformsStartTag + kNumPlatforms; t++) { //error here
CCSprite *platform = (CCSprite*)[batchNode getChildByTag:t];
CGSize platform_size = platform.contentSize;
CGPoint platform_pos = platform.position;
max_x = platform_pos.x - platform_size.width/2 - 10;
min_x = platform_pos.x + platform_size.width/2 + 10;
float min_y = platform_pos.y + (platform_size.height+bird_size.height)/2 - kPlatformTopPadding;
if(bird_pos.x > max_x &&
bird_pos.x < min_x &&
bird_pos.y > platform_pos.y &&
bird_pos.y < min_y) {
[self jump];
}
}
(void) for(t; t < kCloudsStartTag + kNumClouds; t++) { //error here
CCSprite *cloud = (CCSprite*)[batchNode getChildByTag:t];
CGPoint pos = cloud.position;
pos.y -= delta * cloud.scaleY * 0.8f;
if(pos.y < -cloud.contentSize.height/2) {
currentCloudTag = t;
[self resetCloud];
} else {
cloud.position = pos;
}
}
The error is found where the "for" code is. I put the (void) code in because I will get an Expression result unused error. Any ideas?
The (void) before the for loop does not make sense.
You have to remove the (void) before the for loop because it's not a valid c syntax. You can't solve an error with another error.
You may ask the question : Why puting (void) before the for loop prevented the unused expression error. Well that's because the debugger didn't reach it. and it doesn't know for what is for as he expected a resulted value from it to cast it to void.
When the compiler is generating the error: Unused Entity Issue - Expression result unused. That's means that your program is evaluating an expression without using it.
In your case at the for loop if the t variable is already initialized as you want it, you shouldn't put it at the first part as it will be considired as an unused expression.
for(; t < kPlatformsStartTag + kNumPlatforms; t++) { // keep the first expresion empty
// ...
}
You've already got answers about the bogus (void), but not about the unused expression.
for(t; t < kCloudsStartTag + kNumClouds; t++)
The initial expression here, t, has absolutely no effect, and for that reason has no business being present at all. The value of t is read and immediately discarded, and any decent compiler will optimise that by not even bothering to read t. You do not need an expression here. You can remove it, and write
for(; t < kCloudsStartTag + kNumClouds; t++)
although personally, I might be tempted to go with a while loop instead.
Edit: reading your code more closely, your code seems to need to give t an initial value.
for(t = 0; t < kCloudsStartTag + kNumClouds; t++)
Either way, your attempt to suppress the warning without understanding what the warning was telling you wasn't a good idea.

How do you check if an NSInteger is greater than another NSinteger?

I'm trying to write code that detects if an integer is greater than another integer. Is this possible?
Here is what i've done so far.
if (NumCorrect >> NumWrong) {
btnCool.title = #"Awww";
}
else {
btnCool.title = #"Cool!";
}
All its doing is going to the else
EDIT:
NSString *numCorrect = [NSString stringWithFormat:#"%d",NumCorrect];
NSString *numWrong = [NSString stringWithFormat:#"%d", NumWrong];
lblWrong.text = numWrong;
lblCorrect.text = numCorrect;
if (NumCorrect > NumWrong) {
btnCool.title = #"Awww";
} else {
btnCool.title = #"Cool!";
}
Use single >
if (NumCorrect > NumWrong) {
btnCool.title = #"Awww";
} else {
btnCool.title = #"Cool!";
}
Double >> is a bit shift operation. You shift every bit in the binary representation of your variable NumCorrect NumWrong amount of bytes to the right. In almost all cases this will return in a number other then 0, which will then treated as a false value and thus the else block is executed.
Almost perfect - just take off one of those >'s. >> and << are for "bit-shifting", a weird hold-over from the earliest days of programming. You're not gonna use them much. What you really want is > and <, which is for testing if numbers are greater than each other or less than each other.
In addition, you may remember from math class that ≥ and ≤ (greater-than-or-equal-to and less-than-or-equal-to) are useful operations as well. Because there's no symbols for those on most keyboards, however, C and Xcode use >= and <= instead.
Finally, you may already know this, but to check if two numbers are exactly equal to each other you can use == (because = is used for setting the contents of variables).
Hope that's helpful!