Objective-C changing UILabel text - ios

I make a quiz game.I put a label for question in the screen.When I was trying to change it's text the text didn't change.
QuizScreen.h
#import <UIKit/UIKit.h>
int score = 0;
int lives = 3;
int QuestionSelected = 0;
NSString *AnswerRunning;
#interface QuizScreen : UIViewController
{
IBOutlet UITextField *Answer;
IBOutlet UIButton *Go;
IBOutlet UILabel *Question;
IBOutlet UILabel *Session;
IBOutlet UILabel *Lives;
IBOutlet UILabel *Score;
IBOutlet UIButton *Exit;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
-(IBAction)GoBtn:(id)sender;
-(void)questioning;
#end
QuizScreen.m
#import "QuizScreen.h"
#interface QuizScreen ()
#end
#implementation QuizScreen
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
-(IBAction)GoBtn:(id)sender{
switch (QuestionSelected) {
case 0:
if ([Answer.text isEqualToString: #"YOUR WORD"]){
score = score + 1;
Score.text = [NSString stringWithFormat:#"Score: %i" , score];
Session.text = [NSString stringWithFormat:#"Correct Answer!! Score +1"];
}else{
lives = lives - 1;
Lives.text = [NSString stringWithFormat:#"Lives: %i" , lives];
Session.text = [NSString stringWithFormat:#"Wrong Answer!!! Lives -1"];
}
QuestionSelected = QuestionSelected + 1;
break;
case 1:
if ([Answer.text isEqualToString: #"YOUR WORD"]){
score = score + 1;
Score.text = [NSString stringWithFormat:#"Score: %i" , score];
Session.text = [NSString stringWithFormat:#"Correct Answer!! Score +1"];
}else{
lives = lives - 1;
Lives.text = [NSString stringWithFormat:#"Lives: %i" , lives];
Session.text = [NSString stringWithFormat:#"Wrong Answer!!! Lives -1"];
}
QuestionSelected = QuestionSelected + 1;
break;
case 2:
if ([Answer.text isEqualToString: #"YOUR WORD"]){
score = score + 1;
Score.text = [NSString stringWithFormat:#"Score: %i" , score];
Session.text = [NSString stringWithFormat:#"Correct Answer!! Score +1"];
}else{
lives = lives - 1;
Lives.text = [NSString stringWithFormat:#"Lives: %i" , lives];
Session.text = [NSString stringWithFormat:#"Wrong Answer!!! Lives -1"];
}
QuestionSelected = QuestionSelected + 1;
break;
case 3:
if ([Answer.text isEqualToString: #"YOUR WORD"]){
score = score + 1;
Score.text = [NSString stringWithFormat:#"Score: %i" , score];
Session.text = [NSString stringWithFormat:#"Correct Answer!! Score +1"];
}else{
lives = lives - 1;
Lives.text = [NSString stringWithFormat:#"Lives: %i" , lives];
Session.text = [NSString stringWithFormat:#"Wrong Answer!!! Lives -1"];
}
QuestionSelected = QuestionSelected + 1;
break;
case 4:
if ([Answer.text isEqualToString: #"YOUR WORD"]){
score = score + 1;
Score.text = [NSString stringWithFormat:#"Score: %i" , score];
Session.text = [NSString stringWithFormat:#"Correct Answer!! Score +1"];
}else{
lives = lives - 1;
Lives.text = [NSString stringWithFormat:#"Lives: %i" , lives];
Session.text = [NSString stringWithFormat:#"Wrong Answer!!! Lives -1"];
}
QuestionSelected = QuestionSelected + 1;
break;
case 5:
if ([Answer.text isEqualToString: #"YOUR WORD"]){
score = score + 1;
Score.text = [NSString stringWithFormat:#"Score: %i" , score];
Session.text = [NSString stringWithFormat:#"Correct Answer!! Score +1"];
}else{
lives = lives - 1;
Lives.text = [NSString stringWithFormat:#"Lives: %i" , lives];
Session.text = [NSString stringWithFormat:#"Wrong Answer!!! Lives -1"];
}
QuestionSelected = QuestionSelected + 1;
break;
case 6:
if ([Answer.text isEqualToString: #"YOUR WORD"]){
score = score + 1;
Score.text = [NSString stringWithFormat:#"Score: %i" , score];
Session.text = [NSString stringWithFormat:#"Correct Answer!! Score +1"];
}else{
lives = lives - 1;
Lives.text = [NSString stringWithFormat:#"Lives: %i" , lives];
Session.text = [NSString stringWithFormat:#"Wrong Answer!!! Lives -1"];
}
QuestionSelected = QuestionSelected + 1;
break;
case 7:
if ([Answer.text isEqualToString: #"YOUR WORD"]){
score = score + 1;
Score.text = [NSString stringWithFormat:#"Score: %i" , score];
Session.text = [NSString stringWithFormat:#"Correct Answer!! Score +1"];
}else{
lives = lives - 1;
Lives.text = [NSString stringWithFormat:#"Lives: %i" , lives];
Session.text = [NSString stringWithFormat:#"Wrong Answer!!! Lives -1"];
}
break;
default:
break;
}
}
-(void)questioning {
switch (QuestionSelected) {
case 0:
Question.text = #"You can only keep it once you give it to somebody.What is it?";
break;
case 1:
Question.text = #"Light hides me and darkness kills me.What am I?";
break;
case 2:
Question.text = #"Voiceless it cries,Wingless flutters,Toothless bites,Mouthless mutters.";
break;
case 3:
Question.text = #"What goes in the water black and comes out red?";
break;
case 4:
Question.text = #"It's hard to give up.Remove part of it and you still have a bit.Remove another part, but bit is still there.Remove another and it remains.What is it?";
break;
case 5:
Question.text = #"With pointed fangs I sit and wait,with piercing force I serve out fate.Grabbing bloodless victims, proclaiming my might;physically joining with a single bite.What am I?";
break;
case 6:
Question.text = #"Jasmine has a toaster with two slots that toasts one side of each piece of bread at a time, and it takes one minute to do so.If she wants to make 3 pieces of toast, what is the least amount of time she needs to toast them on both sides?";
break;
case 7:
Question.text = #"A man was born on January 1st, 23 B.C. and died January 2nd, 23 A.D. How old did he live to be?";
break;
default:
break;
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
When I run it and write the answer the label's text doesn't change.I tried stringWithFormat but it doesn't work.The strange part is the session label's text changes.But I couldn't find any differences

It seems that Question label's text changes only in method:
-(void)questioning;
But I can't find where you are calling one. Set breakpoint on entrance of it, mb you are never getting there. As I understood your code [self questioning] should be called in viewDidLoad and at the end of GoBtn: methods.
P.S.
You should pay attention to the Coding Guidelines for Cocoa, General Coding Standards and Conventions. Especially to the naming variables, data types, methods e.t.c. (E.g. variables shouldn't start with capital letter, Class or structures should)

Related

Objective-C random alphabet no repeat

i made a random for A-Z. The random letter is shown in a label. everything works fine. But the letter should not repeat till every letter from A-Z is called.
I´am new in xcode an need a litte help.
heres my code in the .m file.
NSString *letters = #"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-(NSString *) randomStringWithLength:(int) len {
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
for (int i=26; i<len; i++) {
[randomString appendFormat: #"%C", [letters characterAtIndex: arc4random() % [letters length]]]; buchstabeAusgabe.text = randomString;
}
return randomString;}
-(void)neuerGenerator {
int text = rand() %26;
switch (text) {
case 0:
buchstabeAusgabe.text =#"A";
break;
case 1:
buchstabeAusgabe.text =#"B";
break;
case 2:
buchstabeAusgabe.text =#"C";
break;
case 3:
buchstabeAusgabe.text =#"D";
break;
case 4:
buchstabeAusgabe.text =#"E";
break;
case 5:
buchstabeAusgabe.text =#"F";
break;
case 6:
buchstabeAusgabe.text =#"G";
break;
case 7:
buchstabeAusgabe.text =#"H";
break;
case 8:
buchstabeAusgabe.text =#"I";
break;
case 9:
buchstabeAusgabe.text =#"J";
break;
case 10:
buchstabeAusgabe.text =#"K";
break;
case 11:
buchstabeAusgabe.text =#"L";
break;
case 12:
buchstabeAusgabe.text =#"M";
break;
case 13:
buchstabeAusgabe.text =#"N";
break;
case 14:
buchstabeAusgabe.text =#"O";
break;
case 15:
buchstabeAusgabe.text =#"P";
break;
case 16:
buchstabeAusgabe.text =#"Q";
break;
case 17:
buchstabeAusgabe.text =#"R";
break;
case 18:
buchstabeAusgabe.text =#"S";
break;
case 19:
buchstabeAusgabe.text =#"T";
break;
case 20:
buchstabeAusgabe.text =#"U";
break;
case 21:
buchstabeAusgabe.text =#"V";
break;
case 22:
buchstabeAusgabe.text =#"W";
break;
case 23:
buchstabeAusgabe.text =#"X";
break;
case 24:
buchstabeAusgabe.text =#"Y";
break;
case 25:
buchstabeAusgabe.text =#"Z";
break;
default:
break;
}}
instead of the switch, perhaps store the alphabet in an NSMutableArray. When a letter is taken, remove it from the array. Instead of %26 do %[array count]. To look up the item in array, use [array objectAtIndex:index] where index is the random number.
I am not on XCode at the moment, but I'll try to write out the full code:
- (NSString *) randomStringWithLength:(int) len andAlphabet: (NSString *) alphabet {
NSMutableArray *alphabetArrayMut = [[self arrayFromString: alphabet] mutableCopy];
NSMutableString *resultString = [NSMutableString stringWithString:#""];
while([alphabetArrayMut count]&&[resultString length]<len){
int index = rand() % [alphabetArrayMut count];
NSString *charToAdd = [alphabetArrayMut objectAtIndex:index];
[resultString appendString:charToAdd];
[alphabetArrayMut removeObjectAtIndex:index];
}
return [resultString copy];
}
- (NSArray *) arrayFromString: (NSString *) string{
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[string length]];
for (int i=0; i < [string length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:i]];
[characters addObject:ichar];
}
return [characters copy];
}
Note that it is probably a lot easier to use recursion. Unfortunately, I am not on my mac at the moment, so I can't test it:
- (NSString *) randomStringWithLength:(int) len andAlphabet: (NSString *) alphabet {
if(len <= 0 || ![alphabet count]){ // base case
return #"";
}
int index = rand() % [alphabet count];
NSString *chosenLetter = [alphabet substringWithRange:NSMakeRange(index, 1)];
NSString *newAlphabet = [alphabet stringByReplacingCharactersInRange:NSMakeRange(index, 1) withString:#""];
NSString *resultString = [NSString stringWithFormat:#"%#%#",chosenLetter,[self randomStringWithLength:len-1,newAlphabet];
return resultString;
}
Lots of different ways to do this. My suggestion would be to use a mutable array:
Add this statement to your .h file:
NSMutableArray *randomLetters;
And then add this method to your .m file:
(Code edited to clean up a ton of typos and minor mistakes)
- (NSString *) randomLetter;
{
if (randomLetters == nil)
randomLetters = [NSMutableArray arrayWithCapacity: 26];
if (randomLetters.count == 0)
{
for (unichar aChar = 'A'; aChar <= 'Z'; aChar++)
{
[randomLetters addObject: [NSString stringWithCharacters: &aChar length: 1]];
}
}
NSUInteger randomIndex = arc4random_uniform((u_int32_t)randomLetters.count);
NSString *result = randomLetters[randomIndex];
[randomLetters removeObjectAtIndex: randomIndex];
return result;
}
(Disclaimer: I typed that code out in the SO editor. I haven't tried to compile it, so it may contain minor typos.)
The method randomLetter will give you a single, non-repeating random letter every time you call it, until the array of remaining random letters is empty. At that point it will repopulate the array with the full alphabet and start over.
The random number generator arc4random_uniform() gives much better results that rand(), and doesn't suffer from "modulo bias" (link) like the expression rand()%range does.
Note that it is possible for the above method to give you the last random letter (an "a", for example") then on the next call, repopulate the array, and give you another "a" from the newly populated array. However, the odds of that happening are only 1 in 26.
You could tweak the above code so it remembers the last character it gives you and doesn't give you that same character twice in a row if that's important.
You could pretty easily change it slightly so that it would give you letters one at a time until it's empty and then return nil, and then write a separate method to fill it. That way you could get exactly 26 non-repeating characters and know when you about to repeat with another set of 26 characters.
because c string is terminal by '\0', we need 27 bytes.
NSString *alp = #"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char cstr[27];
[alp getCString:cstr maxLength:27 encoding:NSUTF8StringEncoding];
// do i from 25 to 0. to 1 is ok, also
for (int i = alp.length - 1; i >= 0; --i) {
int mark = arc4random_uniform(i);
char temp = cstr[i];
cstr[i] = cstr[mark];
cstr[mark] = temp;
}
NSString *str = [NSString stringWithUTF8String:cstr];
NSLog(#"%#", str);
Given these methods:
- (NSString *)stringOfRandomLettersWithLength:(NSUInteger)length {
if (length > 26) {
return nil;
}
NSMutableString *stringOfRandomLetters = [NSMutableString stringWithCapacity:length];
NSArray *letters = #[ #"A", #"B", #"C", #"D", #"E", #"F", #"G", #"H", #"I", #"J", #"K", #"L", #"M", #"N", #"O", #"P", #"Q", #"R", #"S", #"T", #"U", #"V", #"W", #"X", #"Y", #"Z" ];
NSMutableArray *unusedLetters = [letters mutableCopy];
NSString *randomLetter;
for (int i=0; i<length; i++) {
randomLetter = [self randomItemFromArray:unusedLetters];
[unusedLetters removeObject:randomLetter];
[stringOfRandomLetters appendString:randomLetter];
}
return stringOfRandomLetters;
}
- (NSString *)randomItemFromArray:(NSArray *)items {
if (items.count < 1) {
return nil;
}
return items[ arc4random_uniform((u_int32_t)items.count) ];
}
You could create a string of random, distinct letters like this:
NSString *label = [self stringOfRandomLettersWithLength:26];
NSLog(#"label= %#", label);
In the console you'd see something like this:
label= YGRHCXTFDZLKNPAIEOJSUQWVMB

Doing calculations with NSNumbers in a calculator?

Im trying to do the calculations using NSNumbers and keep track of the numbers that the user inputs..
The problem is that my app is not doing any calculations now after updated my code to append . the decimal value to value whenever the user press the dot button. Which can be found Append or Add the decimal point functionality in calculator.
I have seen that the proper way to keep track of the inputs from the user and do the calculation is using the NSNumber but as I'm really new to Objective-c I have been struggling understanding the use and implementing it.
So, hopefully someone could walk me through to find the proper solution.
This is the header...
int Method;
float SelectNumber;
float RunningTotal;
bool DecimalActived;
#interface ViewController : UIViewController{
IBOutlet UILabel *Screen;
}
-(IBAction)Number9:(UIButton *)sender;
-(IBAction)Dot:(UIButton *)sender;
#end
This is the the implementation file..
-(IBAction)Number9:(UIButton *)sender{
[self appendDigit:#"9"];
}
- (IBAction)Dot:(UIButton *)sender {
NSString *currentText = Screen.text;
if ([currentText rangeOfString:#"." options:NSBackwardsSearch].length == 0) {
[self appendDigit:#"."];
}
}
- (void)appendDigit:(NSString *)digit {
// handle two special cases: append to only zero means just replace
// but append decimal point to zero is a regular append
if ([self->Screen.text isEqualToString:#"0"] && ![digit isEqual:#"."]) {
self->Screen.text = digit;
} else {
self->Screen.text = [Screen.text stringByAppendingString:digit];
}
}
- (IBAction)Percent:(UIButton *)sender {
[self MySwitch];
Method = 5;
SelectNumber = 0;
DecimalActived = FALSE;
Screen.text = [NSString stringWithFormat:#"%.2g", RunningTotal];
}
- (IBAction)PositiveOrNegative:(UIButton *)sender {
[self MySwitch];
Method = 6;
SelectNumber = 0;
DecimalActived = FALSE;
Screen.text = [NSString stringWithFormat:#"%g", RunningTotal];
}
-(IBAction)Equals:(UIButton *)sender{
[self MySwitch];
Method = 0;
SelectNumber = 0;
DecimalActived = FALSE;
Screen.text = [NSString stringWithFormat:#"%g", RunningTotal];
}
-(IBAction)AllClear:(UIButton *)sender{
Method = 0;
RunningTotal = 0;
SelectNumber = 0;
Screen.text = [NSString stringWithFormat:#"0"];
}
- (double) MySwitch {
NSNumberFormatter SelectNumber = [[NSNumberFormatter alloc] init];
[SelectNumber setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber RunningTotal = [SelectNumber numberFromString:self->Screen.text];
if (RunningTotal == 0) {
RunningTotal = SelectNumber;
} else{
switch (Method) {
case 1:
RunningTotal = RunningTotal * SelectNumber;
break;
case 2:
RunningTotal = RunningTotal / SelectNumber;
break;
case 3:
RunningTotal = RunningTotal - SelectNumber;
break;
case 4:
RunningTotal = RunningTotal + SelectNumber;
break;
case 5:
RunningTotal = RunningTotal / 100;
break;
case 6:
if(RunningTotal > 0){
RunningTotal = - RunningTotal;
} else{
RunningTotal = + RunningTotal;
}
break;
default:
break;
}
}
return RunningTotal;
}
If you guys have any question or need more information regarding my program please feel free to ask and I will provide as much information as possible or answer any questions that you guys may have.. :)
The header should look more like this:
// this uses more conventional (lowercase) property names
// and removes a couple that looked extraneous
#interface ViewController : UIViewController
#property(strong,nonatomic) IBOutlet UILabel *screen;
#property(assign,nonatomic) NSInteger method;
#property(strong,nonatomic) NSNumber *runningTotal;
#end
As the user presses digits, decimal, minus sign, append to the screen label as you have it. When the user presses an operation button, record an integer for the operation and record the current (NSNumber) value of the screen label. To do a computation...
- (void)doComputation {
float screenF = [[self screenValue] floatValue];
float runningF = [self.runningTotal floatValue];
float result;
switch (self.method) {
case 1:
result = runningF * screenF;
break;
case 2:
result = (screenF == 0.0)? 0.0 : runningF / screenF;
break;
case 3:
result = runningF - screenF;
break;
case 4:
result = runningF + screenF;
break;
default:
break;
}
self.screen.text = [NSString stringWithFormat:#"%0.8f", result];
self.runningTotal = [NSNumber numberWithFloat:result];
}
(screen value, as you have it...)
- (NSNumber *)screenValue {
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
return [f numberFromString:self.screen.text];
}
How does this work?
NSNumberFormatter SelectNumber = [[NSNumberFormatter alloc] init];
[SelectNumber setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber RunningTotal = [SelectNumber numberFromString:self->Screen.text];
if (RunningTotal == 0) {
RunningTotal = SelectNumber;
} else{
switch (Method) {
case 1:
RunningTotal = RunningTotal * SelectNumber;
break;
This code shouldn't even work. Either SelectNumber is a float or it's a NSNumberFormatter*

Using Gestures with Switch Case (iOS)

I am new to creating apps for the iOS. Recently, I've been working on making a calculator app based on gestures. I am using switch cases to change operations, and I originally had it rigged up with buttons, but now I want to use gestures. Here is my code so far. The opAddition function is the first way I tried it, but it wouldn't switch functions. For example, if I wanted to switch from addition to subtraction, it would only work after the number was inputed. That's why I tried to use Switch-Case, but now I don't know how to link up gestures to them.
#implementation ABViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
calculatorScreen.adjustsFontSizeToFitWidth = YES;
self.notification.layer.cornerRadius = 90;
self.notification.layer.masksToBounds = YES;
self.notification.alpha = 0;
[[self.notification layer] setBorderWidth:8.0f];
[[self.notification layer] setBorderColor:[UIColor whiteColor].CGColor];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - buttons
-(IBAction)buttonDigitPressed:(id)sender{
currentNumber = currentNumber *10 + (int)[sender tag];
NSString *number = [NSString stringWithFormat:#"%.1f", currentNumber];
if ( number.length < 11) {
calculatorScreen.text = number;
}
};
#pragma mark - operator button code
-(IBAction)buttonOperationPressed:(id)sender{
if (currentOperation == 0) { result = currentOperation; }
else {
if (_operationSimple.direction == UISwipeGestureRecognizerDirectionUp){
currentOperation = 1;
} else if (_operationSimple.direction == UISwipeGestureRecognizerDirectionDown){
currentOperation = 2;
}
switch (currentOperation) {
case 1:
result = result + currentNumber;
self.notificationText.text = #"+";
[self notify];
break;
case 2:
result = result - currentNumber;
self.notificationText.text = #"-";
[self notify];
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:#"%.1f", result];
if ( [sender tag] == 0) { result = 0; }
currentNumber = [sender tag];
};
#pragma mark - Cancelations
-(IBAction)cancelInput{
currentNumber = 0;
self.notificationText.text = #"C";
[self notify];
calculatorScreen.text = #"0.0";
result = 0.0;
NSLog(#"Cancel Input");
}
-(IBAction)cancelOperation{
currentNumber = 0;
self.notificationText.text = #"AC";
[self notify];
calculatorScreen.text = #"0.0";
currentOperation = 0;
NSLog(#"Clear Operation");
}
double newresult = 0;
#pragma mark - Operations
-(IBAction)opAddition{
result = result + currentNumber;
self.notificationText.text = #"+";
[self notify];
newresult = result;
currentNumber = 0;
NSLog(#"Number Added. New result:");
NSLog([NSString stringWithFormat:#"%2f", newresult]);
calculatorScreen.text = [NSString stringWithFormat:#"%.1f", result];
}
#pragma mark - notification stuffs
- (void)notify{
[UIView animateWithDuration:1.0 animations:^{
self.notification.alpha = 1.0f;
}];
[UIView animateWithDuration:1.0 animations:^{
self.notification.alpha = 0.0f;
}];
}
#end

how to realize several answers in quiz?

I have created a quiz with 4 answers and one of them is right answer. Questions and answers I keep in plist.( where It have arrays of dictionaries).
Now I want to have more than one right answer to one question. Example: User can select A B C D or A C or B C D etc. and push button "next question".
Please tell me the right way to realize my mission!
Sorry for my ENG, I am Russian.
m.file
enter code here- (void)showNextQuestion
{
if ([self.highScore integerForKey:#"HighScore"]<numCorrect){
[self.highScore setInteger:numCorrect forKey:#"HighScore"];
[self.highScore synchronize];
}
currentQuestion++; //= arc4random()%10;
if (currentQuestion <= [self.questions count]){
self.labelScore.text = [NSString stringWithFormat:#"%d", numCorrect];
self.labelHighestScore.text = [NSString stringWithFormat:#"%d", [self.highScore integerForKey:#"HighScore"]];
NSDictionary* nextQuestion = [self.questions objectAtIndex: currentQuestion];//[self.questions objectForKey:[NSString stringWithFormat:#"%d", currentQuestion]];
NSString* correctAnswer = [nextQuestion objectForKey:#"CorrectAnswer"];
self.answer = correctAnswer;
self.labelA.text = [nextQuestion objectForKey:#"A"];
self.labelB.text = [nextQuestion objectForKey:#"B"];
self.labelC.text = [nextQuestion objectForKey:#"C"];
self.labelD.text = [nextQuestion objectForKey:#"D"];
self.labelQuestion.text = [nextQuestion objectForKey:#"QuestionTitle"];
NSLog(#"%d количество вопросов", countQuestion);
int questNumber = countQuestion+1;
NSString *questNumberString = [[NSString alloc] initWithFormat:#"%d", questNumber];
NSLog(#"%#", questNumberString);
questNum.text = questNumberString;
- (IBAction)buttonPressedA:(id)sender {
//AudioServicesPlaySystemSound(SoundID1);
countQuestion++;
if([self.answer isEqualToString: #"A" ]){
numCorrect += 1;
self.labelScore.text = [NSString stringWithFormat:#"%d", numCorrect];
}
[self showNextQuestion];
}
- (IBAction)buttonPressedB:(id)sender {
// AudioServicesPlaySystemSound(SoundID1);
countQuestion++;
if([self.answer isEqualToString: #"B"]){
numCorrect += 1;
self.labelScore.text = [NSString stringWithFormat:#"%d", numCorrect];
}
[self showNextQuestion];}
- (IBAction)buttonPressedC:(id)sender {
//AudioServicesPlaySystemSound(SoundID1);
countQuestion++;
if([self.answer isEqualToString: #"C"]){
numCorrect += 1;
self.labelScore.text = [NSString stringWithFormat:#"%d", numCorrect];
}
[self showNextQuestion];}
- (IBAction)buttonPressedD:(id)sender {
//AudioServicesPlaySystemSound(SoundID1);
countQuestion++;
if([self.answer isEqualToString: #"D"]){
numCorrect += 1;
self.labelScore.text = [NSString stringWithFormat:#"%d", numCorrect];
}
[self showNextQuestion];}
#end
Inside your plist, make the answer itself a dictionary. Use one key/value pair for the title and the other one to indicate if it is correct or not.
When the user selects an answer, you just have to check the corresponding boolean value (in this case "correct").

How do I change the number of decimal places iOS?

I have a simple calculator app and I want it to be so that if the answer requires no decimal places, there are none, just whole numbers. If the answer was 2, I don't want it to say 2.000000, it should say 2. If it requires one decimal place, it should show to one decimal place for example 12.8 instead of 12.80. How would I do this? Here is my code.
btw, this is from a tutorial at http://www.youtube.com/watch?v=Ihw0cfNOrr4, not my own work.
viewcontroller.h
#import <UIKit/UIKit.h>
interface calcViewController : UIViewController {
float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
#end
in the .m
#import "calcViewController.h"
#implementation calcViewController
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"%2f", currentNumber];
}
-(IBAction)buttonOperationPressed:(id)sender {
if (currentOperation ==0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:#"%2f", result];
if ([sender tag] ==0) result=0;
currentOperation = [sender tag];
}
-(IBAction)cancelInput {
currentNumber =0;
calculatorScreen.text = #"0";
}
-(IBAction)cancelOperation {
currentNumber = 0;
calculatorScreen.text = #"0";
currentOperation = 0;
}
One way is to use NSNumberFormatter to format your result instead of NSString's -stringWithFormat::
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:requiredDigits];
[formatter setMinimumFractionDigits:0];
NSString *result = [formatter stringFromNumber:[NSNumber numberWithFloat:currentNumber];
The easiest way is just use [[NSNumber numberWithFloat:] stringValue]
Example:
float someFloatValue;
NSString floatWithoutZeroes = [[NSNumber numberWithFloat:someFloatValue] stringValue];
If we use %g in place of %f will truncate all zeros after decimal point.
For example
[NSString stringWithFormat:#"%g", 1.201000];
Output
1.201
This should work
NSString *result = [#(currentNumber) description];
I had the same problem. This is the code snippet that solved it (looks a lot like Caleb's solution, but that one didn't work for me, so I had to add an extra line):
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = kCFNumberFormatterDecimalStyle;
numberFormatter.maximumFractionDigits = 20;
numberFormatter.minimumFractionDigits = 0;
NSNumber *number = [[NSNumber alloc]init];
NSString *numberString = [numberFormatter stringFromNumber:number];
We can use another numberStyle and override its basic appearance, setting desired properties of an NSNumberFormatter.

Resources