Adding integers and displaying in a UILabel - ios

I am working on a scoreboard of sorts. The player can adjust three different values (gear, level, and bonuses) that when added should provide a total strength. Each of these values is currently being output as an integer and a UILabel displays its' respective integer. I cannot figure out how to add all three integers and then display them on a UILabel. I am currently developing for iOS 7 but I don't imagine this to be terribly different for current supported OS's. Any help is greatly appreciated.
.h
#import <UIKit/UIKit.h>
int levelCount;
int gearCount;
int oneShotCount;
int totalScoreCount;
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *totalScore;
#property (weak, nonatomic) IBOutlet UILabel *playerName;
#property (weak, nonatomic) IBOutlet UILabel *levelNumber;
#property (weak, nonatomic) IBOutlet UILabel *gearNumber;
#property (weak, nonatomic) IBOutlet UILabel *oneShotNumber;
- (IBAction)levelUpButton:(id)sender;
- (IBAction)levelDownButton:(id)sender;
- (IBAction)gearUpButton:(id)sender;
- (IBAction)gearDownButton:(id)sender;
- (IBAction)oneShotUpButton:(id)sender;
- (IBAction)oneShotDownButton:(id)sender;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
int ans = levelCount + gearCount + oneShotCount;
self.levelNumber.text = [NSString stringWithFormat:#"%i", ans];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)levelUpButton:(id)sender {
levelCount = levelCount + 1;
self.levelNumber.text = [NSString stringWithFormat:#"%i", levelCount];
}
- (IBAction)levelDownButton:(id)sender {
levelCount = levelCount - 1;
self.levelNumber.text = [NSString stringWithFormat:#"%i", levelCount];
}
- (IBAction)gearUpButton:(id)sender {
gearCount = gearCount + 1;
self.gearNumber.text = [NSString stringWithFormat:#"%i", gearCount];
}
- (IBAction)gearDownButton:(id)sender {
gearCount = gearCount - 1;
self.gearNumber.text = [NSString stringWithFormat:#"%i", gearCount];
}
- (IBAction)oneShotUpButton:(id)sender {
oneShotCount = oneShotCount + 1;
self.oneShotNumber.text = [NSString stringWithFormat:#"%i", oneShotCount];
}
- (IBAction)oneShotDownButton:(id)sender {
oneShotCount = oneShotCount - 1;
self.oneShotNumber.text = [NSString stringWithFormat:#"%i", oneShotCount];
}
#end

Create some sort of updateScore method that is called anytime one of the other values change.
- (void)updateScore {
totalScoreCount = ... // calculate score from levelCount, gearCount, and oneShotCount
self.totalScore.text = [NSString stringWithFormat:#"%i", totalScoreCount];
}
Then in each of your ...UpButton: and ...DownButton: methods you call:
[self updateScore];
Be sure to call this after updating the other value first. Example:
- (IBAction)levelUpButton:(id)sender {
levelCount = levelCount + 1;
self.levelNumber.text = [NSString stringWithFormat:#"%i", levelCount];
[self updateScore];
}

Related

Make a timer with ranking in Objective-C

I want a ranking in my app where you can see who has the fastest lap.
I try to convert the time into milliseconds, but it didn't work well.
This is my code at the moment.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize watch,start,reset;
- (void)viewDidLoad {
[super viewDidLoad];
running = NO;
count = 0;
watch.text = #"00:00.00";
start.layer.cornerRadius = 45;
reset.layer.cornerRadius = 45;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)startpressed:(id)sender {
if (running == NO) {
running = YES;
[start setTitle:#"STOPP" forState:UIControlStateNormal];
NSDate *watch = [NSDate dateWithTimeIntervalSince1970:(1273636800 / 1000.0)];
if (myTimer == nil) {
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.0055
target:self
selector:#selector(updateTimer)
userInfo: nil
repeats:YES];
}
} else {
running = NO;
[myTimer invalidate];
myTimer = nil;
[start setTitle:#"START" forState:UIControlStateNormal];
}
}
- (IBAction)resetpressed:(id)sender {
running =NO;
[myTimer invalidate];
myTimer =nil;
[start setTitle:#"START" forState:UIControlStateNormal];
count = 0;
watch.text = #"00:00.00";
}
- (void)updateTimer {
count++;
int min = floor(count/100/60);
int sec = floor(count/100);
int mSec = count % 100;
if (sec >= 60) {
sec = sec % 60;
}
watch.text = [NSString stringWithFormat:#"%02d:%02d.%02d", min,sec,mSec];
}
#end
this is my ViewController.h code:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
NSTimer *myTimer;
BOOL running;
int count;
double methodStart;
}
#property (weak, nonatomic) IBOutlet UILabel *watch;
#property (weak, nonatomic) IBOutlet UIButton *start;
#property (weak, nonatomic) IBOutlet UIButton *reset;
#property (weak, nonatomic) IBOutlet UILabel *eins;
#property (weak, nonatomic) IBOutlet UILabel *zwei;
#property (weak, nonatomic) IBOutlet UILabel *drei;
- (IBAction)startpressed:(id)sender;
- (IBAction)resetpressed:(id)sender;
- (void) updateTimer;
#end
Create array for holding lap history in class interface/extension and initialise it.
self.lapHistory = [#[] mutableCopy];
Capture and sort every lap time when lap is reset/stopped
- (IBAction)resetpressed:(id)sender {
[self.lapHistory addObject:#(count)];
self.lapHistory = [self.lapHistory sortedArrayUsingSelector: #selector(compare:)];
}
Display sorted ranking from lapHistory
-(void)displayRanking{
NSMutableString *rankingResult = [[NSMutableString alloc] init];
for (NSNumber *lap in self.lapHistory) {
[rankingResult appendString:[NSString stringWithFormat:#"%ld\n",[lap integerValue]]];
}
NSLog(#"Ranking result is %#", rankingResult);
}

IOS/Objective-C: Can't match users input to Array(index)

I´m learning IOS/Objective-C and I have this users input Quizz project; at the moment I can show all questions and answers (with buttons and labels). But as for the next step - user inputs the answer and gets Right or Wrong - something is missing; I cant seem to match the user´s input to the index. If I write something, the output is always "Wrong". The code:
#import "QuizzViewController.h"
#import "Question.h"
#interface QuizzViewController ()
#property (weak, nonatomic) IBOutlet UILabel *questionLabel;
#property (weak, nonatomic) IBOutlet UILabel *answerLabel;
#property NSArray *questions;
#property NSUInteger index;
#property (weak, nonatomic) IBOutlet UILabel *answerValidation;
#property (weak, nonatomic) IBOutlet UITextField *inputAction;
#property (weak, nonatomic) IBOutlet UIButton *answerButton;
#end
#implementation QuizzViewController
- (void)viewDidLoad {
[super viewDidLoad];
_questions = #[
[Question question:#"Best surfer in the World?" answer:#"Kelly Slater"],
[Question question:#"Capital of England?" answer:#"London"],
[Question question:#"Capital of Argentina?" answer:#"Buenos Aires"]
];
_index = -1;
[self nextQuestionAction];
}
- (IBAction)answerAction:(UIButton *)sender {
Question *question = [_questions objectAtIndex:_index];
NSString *correct=#"Correct";
NSString *wrong=#"Wrong";
_inputAction.text=question.answer;
if (question.answer==_inputAction.text){
_answerValidation.text=correct;
}else{
_answerValidation.text=wrong;
}
}
/*- (IBAction)inputAction:(UITextField *)sender {
Question *question = [_questions objectAtIndex:_index];
NSString *correct=#"Correct";
NSString *wrong=#"Wrong";
if (question.answer==_inputAction.text){
_answerValidation.text=correct;
}else{
_answerValidation.text=wrong;
}
}*/
- (IBAction)nextQuestionAction {
_index = (_index + 1) % _questions.count;
Question *question = [_questions objectAtIndex:_index];
_questionLabel.text = question.question;
_answerLabel.text = #"...";
}
- (IBAction)showAnswerAction {
Question *question = [_questions objectAtIndex:_index];
_answerLabel.text = question.answer;
}
#end
I guess I need to point the index, but I've tried in different ways, and it's not working...Thanks for the help
The answer, with the help of Larme:
- (IBAction)answerAction:(UIButton *)sender {
Question *question = [_questions objectAtIndex:_index];
NSString *correct=#"Correct";
NSString *wrong=#"Wrong";
_inputAction.text=question.answer;
if ([question.answer isEqualToString:_inputAction.text]){
_answerValidation.text=correct;
}else{
_answerValidation.text=wrong;
}
}
The comparinson has to be made with the "isEqualToString" method

Object being populated shows null fields in log (IOS, OBJ-C)

I'm populating an object's fields from Labels, when displaying in Log the label is the correct value, but the object's field is null. I'm coming over from an Android/ Java background and this is just awkward.
Any help would be great.
To be clear, the "soil type field" log shows "example"while the "soil type" log shows (null)
- (IBAction)saveButton:(id)sender {
Soil *thisSoil = self.thisSoil;
thisSoil.soilType = self.soilNameField.text;
NSLog(#"soil type field %#", self.soilNameField.text);
NSLog(#"soil type: %#", thisSoil.soilType);
thisSoil.frictionAngle = [self.frictionAngleValue.text integerValue];
if ([self.soilUnitsSwitch isOn] ) {
thisSoil.cohesion = [self.cohesionValue.text doubleValue];
thisSoil.unitWeight = [self.unitWeightValue.text doubleValue];
}else{
thisSoil.cohesion = [self.cohesionValue.text doubleValue];
thisSoil.unitWeight = [self.unitWeightValue.text doubleValue];
}
[self.delegate SoilCreatorViewController:self didFinishItem:thisSoil];
[self.navigationController popViewControllerAnimated:YES];
}
The entire controller .m file
#import "SoilCreatorViewController.h"
#define IMPERIAL_TO_METRIC 0.3048
#define KG_TO_LBS 2.2
#interface SoilCreatorViewController ()
#end
#implementation SoilCreatorViewController
- (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 from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)soilQuestions:(id)sender {
[self popupmaker :#"Friction Angle" : #"Phi is the angle of internal friction for soil, which governs soil strength and resistance. This value should be attained from competent field testing and the judgment of a licensed engineer."];
[self popupmaker :#"Soil Cohesion": #"Cohesion defines the non-stress dependent shear strength of soil and should be used with caution. Typically,cohesion occurs in stiff, over-consolidated clays or cemented native soils. Cohesion should be neglected if the designer is unsure of its presence."];
}
- (IBAction)SwitchDidChange:(id)sender {
if ([sender isOn]) {
self.cohesionUnits.text = #"Ft";
self.unitWeightUnits.text= #"M";
}else{
self.cohesionUnits.text = #"M";
self.unitWeightUnits.text = #"M";
}
}
- (IBAction)unitWtDidChange:(id)sender {
self.unitWeightValue.text = [NSString stringWithFormat:#"%.1f", (double)self.unitWeightStepper.value];
}
- (IBAction)frictionAngleDidChange:(id)sender {
self.frictionAngleValue.text = [NSString stringWithFormat:#"%d", (int)self.frictionAngleStepper.value];
}
- (IBAction)cohesionDidChange:(id)sender {
self.cohesionValue.text = [NSString stringWithFormat:#"%.1f", (double)self.cohesionStepper.value];
}
- (IBAction)textFieldDismiss:(id)sender {
[[self view] endEditing:YES];
}
- (IBAction)UnitSwitch:(id)sender {
if ([sender isOn]) {
self.unitWeightUnits.text = #"LBS/cubic Ft.";
self.cohesionUnits.text = #"imp";
}else{
self.unitWeightUnits.text = #"KG/m3";
self.cohesionUnits.text = #"met";
}
}
- (IBAction)cancelButton:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)saveButton:(id)sender {
Soil *thisSoil = self.thisSoil;
thisSoil.soilType = self.soilNameField.text;
NSLog(#"soil type field %#", self.soilNameField.text);
NSLog(#"soil type: %#", thisSoil.soilType);
thisSoil.frictionAngle = [self.frictionAngleValue.text integerValue];
if ([self.soilUnitsSwitch isOn] ) {
thisSoil.cohesion = [self.cohesionValue.text doubleValue];
thisSoil.unitWeight = [self.unitWeightValue.text doubleValue];
}else{
thisSoil.cohesion = [self.cohesionValue.text doubleValue];
thisSoil.unitWeight = [self.unitWeightValue.text doubleValue];
}
[self.delegate SoilCreatorViewController:self didFinishItem:thisSoil];
[self.navigationController popViewControllerAnimated:YES];
}
-(void)popupmaker:(NSString *)title :(NSString *)message{
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil
];
[alert show];
}
#end
The .h file
#import "Soil.h"
#class SoilCreatorViewController;
#protocol SoilCreatorViewDelegate <NSObject>
-(void)SoilCreatorViewController:(SoilCreatorViewController *)controller didFinishItem:(Soil *)item;
#property (nonatomic, weak) id <SoilCreatorViewDelegate> delegate;
#end
#import <UIKit/UIKit.h>
#import "CalculationDetailViewController.h"
#interface SoilCreatorViewController : UIViewController
#property (nonatomic,weak) id<SoilCreatorViewDelegate> delegate;
#property (weak, nonatomic) IBOutlet UITextField *soilNameField;
#property (weak, nonatomic) IBOutlet UISwitch *soilUnitsSwitch;
#property (nonatomic,strong) Soil *thisSoil;
#property (weak, nonatomic) IBOutlet UIStepper *frictionAngleStepper;
#property (weak, nonatomic) IBOutlet UIStepper *unitWeightStepper;
#property (weak, nonatomic) IBOutlet UIStepper *cohesionStepper;
#property (weak, nonatomic) IBOutlet UILabel *unitWeightValue;
#property (weak, nonatomic) IBOutlet UILabel *frictionAngleValue;
#property (weak, nonatomic) IBOutlet UILabel *cohesionValue;
#property (weak, nonatomic) IBOutlet UILabel *unitWeightUnits;
#property (weak, nonatomic) IBOutlet UILabel *cohesionUnits;
- (IBAction)soilQuestions:(id)sender;
- (IBAction)SwitchDidChange:(id)sender;
- (IBAction)unitWtDidChange:(id)sender;
- (IBAction)frictionAngleDidChange:(id)sender;
- (IBAction)cohesionDidChange:(id)sender;
- (IBAction)textFieldDismiss:(id)sender;
- (IBAction)cancelButton:(id)sender;
- (IBAction)saveButton:(id)sender;
-(void)popupmaker:(NSString *)title :(NSString *)message;
#end
I don't see any code that sets up thisSoil. At some point in your code, you need to write something like
self.thisSoil = [[Soil alloc] init];
or self.thisSoil will stay nil forever.

UIView not updating in iPhone App

I am new to iPhone App development, below is ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self updateMyView];
}
- (IBAction)clickButtonResult:(id)sender
{
enteredText = [textField text]; // Or textField.text
NSLog(#"Number 1 : %i", number_1);
NSLog(#"Number 2 : %i", number_2);
NSLog(#"Entered Text is %#", enteredText);
int NUM_RESULT = number_1 + number_2;
verify_result = [NSString stringWithFormat:#"%i", NUM_RESULT];
NSLog(#"Verify Result : %#", verify_result);
NSString *final_result = [NSString stringWithFormat:#"%d", [enteredText isEqualToString:verify_result]];
int final_int_result = [final_result integerValue];
if (final_int_result) {
//result_label.text = #"Correct";
NSLog(#"Correct");
[self updateMyView];
} else {
//result_label.text = #"Wrong";
NSLog(#"Wrong");
}
}
- (int)getRandomNumberBetween:(int)min maxNumber:(int)max
{
return min + arc4random() % (max - min + 1);
}
- (void) updateMyView
{
number_1 = [self getRandomNumberBetween:10 maxNumber:99];
number_2 = [self getRandomNumberBetween:10 maxNumber:99];
num_1.text = [NSString stringWithFormat:#"%i", number_1];
num_2.text = [NSString stringWithFormat:#"%i", number_2];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
and ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
IBOutlet UILabel *num_1;
IBOutlet UILabel *num_2;
IBOutlet UILabel *result_label;
IBOutlet UITextField *textField;
int number_1;
int number_2;
NSString *verify_result;
NSString *enteredText;
BOOL display_result;
}
- (IBAction)clickButtonResult:(id)sender;
#end
After entering the correct result the UIView should be updated with updateMyView function but it is not happening.
Can anyone help here??
First of all, start using Properties.
ViewController.h
#interface ViewController : UIViewController
#property (nonatomic, weak) IBOutlet UILabel *num_1;
#property (nonatomic, weak) IBOutlet UILabel *num_2;
#property (nonatomic, weak) IBOutlet UILabel *resultLabel;
#property (nonatomic, weak) IBOutlet UITextField *textField;
#property (nonatomic) NSInteger number_1;
#property (nonatomic) NSInteger number_2;
#property (nonatomic, strong) NSString *verifyResult;
#property (nonatomic, strong) NSString *enteredText;
#property (nonatomic) BOOL displayResult;
- (IBAction)clickButtonResult:(id)sender;
#end
In ViewController.m code use self.{name of property}, for example self.textField for the textField property.
Now, go to Interface builder and connect the IBOutlet properties to the right objects. (click with right button on File's Owner)
Try changing num_1.text in viewDidLoad to make sure you have access to that label from your UIViewController.
So in viewDidLoad, just put something like
num1.text = #"Updated from viewDidLoad"
Make sure that you have connected num_1 and num_2 with the UILabels properly. It seems that you have not connected these.
Just move [self updateMyView]; outside the if statements in clickButtonResult: function
then it will update the view when click the button.
if (final_int_result) {
//result_label.text = #"Correct";
NSLog(#"Correct");
} else {
//result_label.text = #"Wrong";
NSLog(#"Wrong");
}
[self updateMyView];

dynamically generated UIButton in iOS 5 ARC causes deallocated instance crash

I have a a class I created to generate UIButton's I add to my UIView. This worked great until my conversion to ARC yesterday, not I get the following error:
-[OrderTypeButton performSelector:withObject:withObject:]: message sent to deallocated instance 0x12449f70
Here is the code to add the button to my UIView (actually a subview in my main UIView):
OrderTypeButton *btn = [[OrderTypeButton alloc]initWithOrderType:#"All Orders" withOrderCount:[NSString stringWithFormat:#"%i",[self.ordersPlacedList count]] hasOpenOrder:NO];
btn.view.tag = 6969;
btn.delegate = self;
[btn.view setFrame:CGRectMake((col * width)+ colspacer, rowHeight + (row * height), frameWidth, frameHeight)];
[self.statsView addSubview:btn.view];
And here is my class header:
#import <UIKit/UIKit.h>
#protocol OrderTypeButtonDelegate
-(void) tapped:(id)sender withOrderType:(NSString*) orderType;
#end
#interface OrderTypeButton : UIViewController {
id<OrderTypeButtonDelegate> __unsafe_unretained delegate;
IBOutlet UILabel *lblOrderType;
IBOutlet UILabel *lblOrderCount;
NSString *orderType;
NSString *orderCount;
BOOL hasOpenOrder;
}
#property (nonatomic, strong) IBOutlet UIButton *orderButton;
#property (nonatomic, strong) IBOutlet UILabel *lblOrderType;
#property (nonatomic, strong) IBOutlet UILabel *lblOrderCount;
#property (nonatomic, strong) NSString *orderType;
#property (nonatomic, strong) NSString *orderCount;
#property (nonatomic, assign) BOOL hasOpenOrder;
#property (nonatomic, unsafe_unretained) id<OrderTypeButtonDelegate> delegate;
-(id) initWithOrderType: (NSString *) anOrderType withOrderCount: (NSString *) anOrderCount hasOpenOrder: (BOOL) openOrder;
-(IBAction)btnTapped:(id)sender;
#end
Implementation:
#import "OrderTypeButton.h"
#implementation OrderTypeButton
#synthesize orderButton;
#synthesize lblOrderType, lblOrderCount, orderType, orderCount, hasOpenOrder, delegate;
-(id) initWithOrderType: (NSString *) anOrderType withOrderCount: (NSString *) anOrderCount hasOpenOrder: (BOOL) openOrder {
if ((self = [super init])) {
self.orderType = anOrderType;
self.orderCount = anOrderCount;
self.hasOpenOrder = openOrder;
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.lblOrderType.text =[NSString stringWithFormat:#"%#", self.orderType];
self.lblOrderCount.text = [NSString stringWithFormat:#"%#", self.orderCount];
if (self.hasOpenOrder) {
[self.orderButton setBackgroundImage:[UIImage imageNamed:#"background-order-btn-red.png"] forState:UIControlStateNormal];
self.lblOrderType.textColor = [UIColor whiteColor];
self.lblOrderCount.textColor = [UIColor whiteColor];
}
}
-(IBAction)btnTapped:(id)sender {
NSLog(#"TAPPED");
if ([self delegate] ) {
[delegate tapped:sender withOrderType:self.orderType];
}
}
- (void)viewDidUnload
{
[self setOrderButton:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#end
This seems fairly simple what I am doing here, not sure what changed with ARC that is causing me problems.
Maybe ARC autorelease created button, try to store created buttons in Array
//.h file
#property (nonatomic, strong) NSArray *buttonsArray
//.m file
#synthesize buttonsArray
...
- (void)viewDidLoad {
buttonsArray = [NSArray array];
...
OrderTypeButton *btn = [[OrderTypeButton alloc]initWithOrderType:#"All Orders"
withOrderCount:[NSString stringWithFormat:#"%i",[self.ordersPlacedList count]]
hasOpenOrder:NO];
btn.view.tag = 6969;
btn.delegate = self;
[btn.view setFrame:CGRectMake((col * width)+ colspacer, rowHeight + (row * height), frameWidth, frameHeight)];
[self.statsView addSubview:btn.view];
//Add button to array
[buttonsArray addObject:btn];
Also this approach will help if you want to change buttons, or remove some specific button from view

Resources