Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have been stuck on a problem for hours now, and can not seem to figure this out. I am new to Objective-C and it is really annoying me that I can not get this. I am trying to get the NSLog values displayed in bmiLabel, but my bmiLabel always shows NULL.
This is my code:
ViewController.h:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITextFieldDelegate>
#property (strong, nonatomic) IBOutlet UITextField *num1;
#property (strong, nonatomic) IBOutlet UITextField *num2;
#property (strong, nonatomic) IBOutlet UILabel *resultLabel;
#property (strong, nonatomic) IBOutlet UILabel *bmiLabel;
- (IBAction)bmiButton:(id)sender;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize num1, num2, resultLabel, bmiLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (IBAction)bmiButton:(id)sender
{
float sum = [self.num2.text floatValue] / ([self.num1.text floatValue] *
[self.num1.text floatValue]);
NSString *Output = nil;
Output = [[NSString alloc] initWithFormat:#"%.2f", sum];
self.resultLabel.text = Output;
NSString *mystring;
NSString * bmi = [[NSString alloc] NSStringWithFormat:#"%#", mystring];
self.bmiLabel.text = bmi;
if(sum <= 18.5)
{
NSLog(#"You are underweight", mystring);
}
if(sum <= 18.5)
{
NSLog(#"you are normal");
}
if (sum <= 25.0)
{
NSLog(#"You are overweight");
}
if(sum <= 30)
{
NSLog(#"You are obese");
}
}
#end
Well, trying to be a little psychic, I note that you're not actually putting anything in the BMI case. Try this instead:
- (IBAction)bmiButton:(id)sender {
float sum = [self.num2.text floatValue] / ([self.num1.text floatValue] *
[self.num1.text floatValue]);
NSString *Output = [NSString stringWithFormat:#"%.2f", sum];
self.resultLabel.text = Output;
NSString *mystring= nil;
if (sum <= 18.5) {
mystring = #"You are underweight";
} else if (sum <= 25.0) {
mystring = #"you are normal";
} else if (sum <= 30.0){
mystring = #"You are overweight";
} else {
mystring = #"You are obese:";
}
self.bmiLabel.text = mystring;
}
I think [[NSString alloc] NSStringWithFormat:#"%#", mystring]; code has a problem. Try below code
NSString *mystring;
NSString * bmi = [NSString stringWithFormat:#"%#", mystring];
self.bmiLabel.text = bmi;
Also you must initialize mystring. If you don't mystring always returns null.
This code is not useful because you bmi is going to be an empty string. So bmiLabel will be empty.
NSString *mystring;
NSString * bmi = [[NSString alloc] NSStringWithFormat:#"%#", mystring];
self.bmiLabel.text = bmi;
The rest of your code is fine. Although in my opinion you use too much objects in your code. For example, Your NSString is not necessary, you can write this
float sum = [self.num2.text floatValue] / ([self.num1.text floatValue] *
[self.num1.text floatValue]);
self.resultLabel.text = [[NSString alloc] initWithFormat:#"%.2f", sum];
This:
[[NSString alloc] NSStringWithFormat:#"%#", mystring];
StringWithFormat is a class method which would be sent to the class:
string = [NSString stringWithFormat:#"some string"];
This tells the class to give you a string which is already allocated and initialized.
In your case you should (can) use:
string = [[NSString alloc]initWithFormat:#"some string"];
Also, about this line in your code:
NSString * bmi = [[NSString alloc] NSStringWithFormat:#"%#", mystring];
you could just do this:
[[self bmiLabel]setText:[[NSString alloc]initWithString:mystring]];
or if you prefer dot notation
self.bmiLabel.text = [[NSString alloc]initWithString:mystring]];
I don't know what you're asking, but there is an error here:
NSString *mystring;
NSString * bmi = [[NSString alloc] NSStringWithFormat:#"%#", mystring];
self.bmiLabel.text = bmi;
First off, your string format setters:
[[NSString alloc] NSStringWithFormat:#"someformat: %#", someVariable];
Should be:
[NSString stringWithFormat:#"someformat: %#", someVariable];
If however, those were correct, this would still have this problem:
NSString * bmi = [NSString stringWithFormat:#"%#", mystring];
Is very strange when mystring is already a string. It's equivelant to:
NSString * bmi = mystring;
Basically, those three lines are equivelant to:
NSString * mystring;
self.bmiLabel.text = mystring;
Answer
The problem is, you never assigned a value to mystring
Related
So I have a custom TVShow object that has some base fields like id, showName, airDate etc. which are all either NSStrings or NSIntegers and I am attempting to create a bunch of these objects via some data I have gotten from an API online.
So I loop through my NSArray of JSON data and create a TVShow object for each response:
TVShow *show = [[TVShow alloc] initWithData:[NSJSONSerialization JSONObjectWithData:data options:0 error:&error]];
[self.showArray addObject:show];
However, only 7 of these ever get created and then any code below this just ceases to run. I have a NSLog(#"Added"); printing after I create the show and it only gets called 6 times. If I add breakpoints after any of this code, they never get called. I'm not sure what's going on but it must be something to do with how I have set up my TVShow object?
It currently looks like:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#interface TVShow : NSObject
#property NSInteger showID;
#property NSString *showName;
#property NSString *airDate;
#property double rating;
#property NSString *imageUrl;
#property NSString *showSummary;
#property NSString *episodeSummary;
#property NSInteger season;
#property NSInteger episode;
- (id)initWithData:(NSDictionary *)data;
#end
and the .m file:
#import <UIKit/UIKit.h>
#import "TVShow.h"
#implementation TVShow
- (id)initWithData:(NSDictionary*)data {
self = [super init];
if(self) {
[self buildObjectFromData:data];
}
return self;
}
-(void)buildObjectFromData:(NSDictionary*)data {
NSDictionary *dict = [data objectForKey:#"_embedded"];
NSDictionary *dict2 = [dict objectForKey:#"nextepisode"];
NSDictionary *dict3 = [data objectForKey:#"image"];
NSString *airDate = [dict2 valueForKey:#"airstamp"];
NSInteger season = [[dict2 valueForKey:#"season"] integerValue];
NSInteger episode = [[dict2 valueForKey:#"episode"] integerValue];
NSString *episodeSummary = [dict2 valueForKey:#"summary"];
NSString *showName = [data valueForKey:#"name"];
NSString *showSummary = [data valueForKey:#"summary"];
NSString *imageUrl = [dict3 valueForKey:#"medium"];
NSInteger showID = [[data valueForKey:#"id"] integerValue];
self.airDate = airDate;
self.showName = showName;
self.season = season;
self.episode = episode;
self.showSummary = [self stringByStrippingHTML:showSummary];
self.episodeSummary = [self stringByStrippingHTML:episodeSummary];
self.imageUrl = imageUrl;
self.showID = showID;
}
-(NSString *) stringByStrippingHTML:(NSString*)string {
NSRange r;
NSString *s = string;
while ((r = [s rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:#""];
return s;
}
#end
If I create the object as just: [[TVShow alloc] init]; everything works fine, so it must be something wrong with this model is what I'm thinking. I'm unsure of what to try next, but any help would be greatly appreciated here.
Turns out there were cases that casued:
-(NSString *) stringByStrippingHTML:(NSString*)string {
NSRange r;
NSString *s = string;
while ((r = [s rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:#""];
return s;
}
to go into infinite loops. Removing this snippet fixed the freeze.
So i recently implemented parallax images into my app which works great, however this has broken a button which calls a method.
Here is a picture of my storyboard:
http://imgur.com/uIonWrK
Here is my .h code:
#interface _01FirstViewController : UIViewController <UITextFieldDelegate, UIAccelerometerDelegate>{
UIAccelerometer *accelerometer;
float xoof;
float yoff;
float xvelocity;
float yvelocity;
float xaccel;
float yaccel;
}
#property (nonatomic, retain) UIAccelerometer *accelerometer;
#property (weak, nonatomic) IBOutlet UIScrollView *BGScrollView;
#property (weak, nonatomic) IBOutlet UIButton *Track;
#property (weak, nonatomic) IBOutlet UITextField *trackingNumber;
#property (strong, nonatomic) NSDictionary *posts;
#property (strong,nonatomic) NSString *TrackPoint;
#property (strong,nonatomic) NSArray *Path;
#property (strong,nonatomic) NSString *documentFolder;
#property (strong,nonatomic) NSString *filePath;
-(void)parseTrackNo;
-(void)reloadTrackingNumber;
Here is the relevant parts of the .m:
- (void)viewDidLoad
{
_BGScrollView.contentSize = CGSizeMake(_BGScrollView.frame.size.width+30,_BGScrollView.frame.size.width+30);
self.accelerometer = [UIAccelerometer sharedAccelerometer];
self.accelerometer.updateInterval = 0.03;
self.accelerometer.delegate = self;
[NSTimer scheduledTimerWithTimeInterval:-1 target:self selector:#selector(tick) userInfo:nil repeats:YES];
}
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
float xx = -acceleration.x;
float yy = (acceleration.y + 0.5f) *2.0f;
float acceldirX;
if (xvelocity * -1.0f >0){
acceldirX = 1.0;
}
else {
acceldirX = -1.0;
}
float newdirX;
if (xx > 0){
newdirX = 1.0;
}
else {
newdirX = -1.0;
}
float acceldirY;
if (yvelocity * -1.0f >0){
acceldirY = 1.0;
}
else {
acceldirY = -1.0;
}
float newDirY;
if (yy > 0){
newDirY = 1.0;
}
else {
newDirY = -1.0;
}
if (acceldirX == newdirX) xoof = acceleration.x * 30;
if (acceldirY == newDirY) yoff = acceleration.y *30;
}
This is the button that has stopped calling the method:
- (IBAction)Track:(id)sender {
[self parseTrackNo]; //Not calling method
NSLog(#"Button Pressed"); //This gets logged correctly
}
I have tried removing all code changes so i suspect it is something to do with the button being nested inside the view in the storyboard or the delegate changes.
Can anyone point me in the correct direction?
EDIT as requested the code for parseTrackingNo (note this was working perfectly until the parallax changes):
-(void)parseTrackNo
{
_01AppDelegate *appDelegate = (_01AppDelegate *)[[UIApplication sharedApplication] delegate];
//Get Tracking Number from textField
appDelegate.TrackingNumber = _trackingNumber.text;
//Check String isn't empty
if ([_trackingNumber.text isEqual: #""]){
} else{
//Check against Royal Mail API
NSString *trackingURL = [NSString stringWithFormat:#"%#%#", #"http://api.e44.co/tracktrace/", appDelegate.TrackingNumber];
NSURL *royalMail = [NSURL URLWithString:trackingURL];
//Return results
NSData *royalMailResults = [NSData dataWithContentsOfURL:royalMail];
//Parse JSON results
if(royalMailResults != nil)
{
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:royalMailResults options:NSJSONReadingMutableContainers error:&error];
if (error == nil)
//Convert to dictionary/array
self.posts = (NSDictionary *)result;
NSArray *trackRecords = _posts[#"trackRecords"];
//Return keys from posts (Dict)
NSString *response = [self.posts valueForKeyPath:#"response"];
NSLog(#"Response: %#", response);
NSString *returnedTrackingNumber = [self.posts valueForKeyPath:#"trackingNumber"];
NSLog(#"Returned tracking number: %#", returnedTrackingNumber);
NSString *delivered = [self.posts valueForKeyPath:#"delivered"];
NSLog(#"delivered: %#", delivered);
NSString *signature = [self.posts valueForKeyPath:#"signature"];
NSLog(#"Signature: %#", signature);
//Track Records
NSString *Date = [trackRecords valueForKeyPath:#"date"];
NSLog(#"date: %#", Date);
NSString *Time = [trackRecords valueForKeyPath:#"time"];
NSLog(#"time: %#", Time);
NSString *Status = [trackRecords valueForKeyPath:#"status"];
NSLog(#"status: %#", Status);
appDelegate.LocationData = [[trackRecords valueForKey:#"trackPoint"] componentsJoinedByString:#""];
NSLog(#"GeoLocation: %#", appDelegate.LocationData);
//Check for Errors returned
if ([self.posts objectForKey:#"errorMsg"]) {
NSLog(#"ERROR MOTHERFUCKER");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"It appears that you have entered an incorrect tracking number"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alert show];
} else {
[self performSegueWithIdentifier:#"addPackageSegue" sender:self];
}
}
}
}
I've been working on an iOS app and I've run into some complications in one of the screens.
This screen, titled "about", has just 2 labels: they're supposed to display the current username and time.
The labels' text loads well but I can't get them to show me the variables with the username and the current time.
Here is my code:
About.h
#interface About : UIViewController
#property (weak) IBOutlet UILabel * username;
#property (weak) IBOutlet UILabel * date;
#property (strong, nonatomic) NSString * usuari;
#property (strong, nonatomic) NSString * data;
#property (strong, nonatomic) NSString * name;
#property (strong, nonatomic) NSString * currentTime;
About.m
#import "About.h"
#interface About()
#end
#implementation About
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel * username = [[UILabel alloc] initWithFrame:CGRectMake(162, 106, 150, 72)];
[self.view addSubview: username];
username.text = #"Usuari: ";
username.numberOfLines = 4;
username.textColor = [UIColor blackColor];
username.text = [NSString stringWithFormat:#"Usuari: ", _usuari];
UILabel * date = [[UILabel alloc] initWithFrame:CGRectMake(160, 261, 1488, 44)];
[self.view addSubview: date];
date.text = #"Hora: ";
date.numberOfLines = 4;
date.textColor = [UIColor blackColor];
date.text = [NSString stringWithFormat:#"Hora: ", _currentTime];
}
-(void) gettingUser
{
[[UIDevice currentDevice] name];
self.username.text = self.name;
}
-(void) gettingTime
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]];
self.date.text = self.currentTime;
//self.date.text = [NSDate date];
//NSTimer schedule interval
//NSDateFormatter alloc
}
#end
Can you help me figure out what do I need to do to make it work?
The reason the variable are not showing is due to no format specifiers. I'm also surprised you didn't receive compiler warnings or errors with the above code.
This line of code:
username.text = [NSString stringWithFormat:#"Usuari: ", _usuari];
Should be written, like this - not so?
username.text = [NSString stringWithFormat:#"Usuari:%# ", _usuari];
As _usuari is the variable and the %# is the format specifier, of where you want to place that variable.
After this: ursername.text should print out like so: Usuari: variable value
How to display an integer value in a UILabel in ViewDidLoad? I did for text and date and image but how to convert int to string. I was trying with following code
NSString* label=[aa stringWithFormat:#"%d",((Comments *) [self.list objectAtIndex:0]).noofcomm]];
[self.comments2 setText:label];
but didn't work.Please help me.How to set with the Integer with UILabel?
This is my comments.h
#interface Comments : NSObject
{
NSInteger iD;
UIImage *photo;
NSString *name;
NSString *descrp;
NSDate *date;
NSString *msg;
NSInteger noofcomm;
NSInteger nooflikes;
}
#property(nonatomic,assign)NSInteger iD;
#property(nonatomic,retain)UIImage *photo;
#property(nonatomic,retain)NSString *name;
#property(nonatomic,retain)NSString *descrp;
#property(nonatomic,strong)NSDate *date;
#property(nonatomic,retain)NSString *msg;
#property(nonatomic,assign)NSInteger noofcomm;
#property(nonatomic,assign)NSInteger nooflikes;
#end
DBClass.m
#import "DBClass.h"
#import "Comments.h"
#implementation DBClass
- (NSMutableArray *) getMyComments{
NSMutableArray *wineArray = [[NSMutableArray alloc] init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"ComntDB.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured.");
}
const char *sql = "SELECT id, photo,name,descrp, time,msg,comments,likes FROM Com";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement");
}
//
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Comments *MyWine = [[Comments alloc]init];
MyWine.iD = sqlite3_column_int(sqlStatement, 0);
const char *raw = sqlite3_column_blob(sqlStatement, 1);
int rawLen = sqlite3_column_bytes(sqlStatement, 1);
NSData *data = [NSData dataWithBytes:raw length:rawLen];
MyWine.photo = [[UIImage alloc] initWithData:data];
MyWine.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
MyWine.descrp = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)];
MyWine.date=[NSDate dateWithTimeIntervalSince1970:sqlite3_column_double(sqlStatement,4)];
MyWine.msg = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,5)];
MyWine.noofcomm = sqlite3_column_int(sqlStatement, 6);
MyWine.nooflikes = sqlite3_column_int(sqlStatement, 7);
[wineArray addObject:MyWine];
}
}
#catch (NSException *exception) {
NSLog(#"An exception occured: %#", [exception reason]);
}
#finally {
return wineArray;
}
}
#end
RootViewController.m
#import "RootViewController.h"
#import "Comments.h"
#import "DBClass.h"
#interface RootViewController ()
#end
#implementation RootViewController
#synthesize list;
#synthesize image2;
#synthesize name2;
#synthesize descrp2;
#synthesize msg2;
#synthesize date2;
#synthesize comments2;
#synthesize likes2;
- (void)viewDidLoad
{
DBClass * mywines =[[DBClass alloc] init];
self.list = [mywines getMyComments];
[self.image2 setImage:((Comments *) [self.list objectAtIndex:0]).photo];
[self.name2 setText:((Comments *) [self.list objectAtIndex:0]).name];
[self.descrp2 setText:((Comments *) [self.list objectAtIndex:0]).descrp];
NSDateFormatter* fmtr = [[NSDateFormatter alloc] init];
[fmtr setDateFormat:#"MM/dd/yy"];
NSString* label_str = [fmtr stringFromDate:((Comments *) [self.list objectAtIndex:0]).date];
[self.date2 setText:label_str];
[self.msg2 setText:((Comments *) [self.list objectAtIndex:0]).msg];
//[self.comments2 setText:((Comments *) [self.list objectAtIndex:0]).noofcomm];
// int solution = 1;
// [self.comments2 setText:[NSString stringWithFormat:#"%d", solution]];
// int solution2 = 1;
// [self.likes2 setText:[NSString stringWithFormat:#"%d", solution2]];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[self setImage2:nil];
[self setName2:nil];
[self setMsg2:nil];
[self setDescrp2:nil];
[self setComments2:nil];
[self setLikes2:nil];
[self setDate2:nil];
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
NSInteger someInteger = myInteger;
NSString *someString = [NSString stringWithFormat:#"%d", someInteger];
myLabel.text = someString;
or
NSNumber *someNumber = #(myInteger);
NSString *someString = [someNumber stringValue];
myLabel.text = someString;
Both will work.
EDIT:
In your case, it will be something like this:
NSInteger someInteger = ((Comments *) [self.list objectAtIndex:0]).noofcomm;
NSString someString = [NSString stringWithFormat:#"%d", someInteger];
self.comments2.text = someString;
If it's still not working, FOR SURE the problem is somewhere else, and not with the conversion. Check with property noofcomm has a valid value, check if your label reference is ok (test with a random value before the conversion), and somethings like that.
You need to build an NSString
int someInteger = 10;
NSString *someString = [[NSString alloc] initWithFormat:#"%d", someInteger];
You can use something like [NSString string_from_int:42] in LCategory since 0.1.3: https://github.com/superarts/LCategory
_lbl_yourLabel.text=[NSString stringWithFormat:#"%d",[[dic valueForKey:#"your integer value"] intValue]];
On the top left is your label named "yourLabel" , "dic" is your json response dictionary where all the data is coming in key value terms, "your integer value" is the key for which the value will be assign to the label "yourLabel", we have taken intValue because we cannot assign integer value directly to the label.
or you also can try below:
int anyInteger = 13;
NSString *yourString = [[NSString alloc] initWithFormat:#"%d", anyInteger];
self.yourLabel.text = yourString;
Newbie error?
Im working on a quiz app that uses answer results from a view contoller, creates NSMutableArray objects for totalCorrect and totalTried values in a KeepScore model .m file and the model returns a score back to my view controller. The view controller then updates my score label in my view. I then use the UINavigationController to segue to my next view controller and then wait for the user to input the next quiz question answer. Problem is that the next time i call my KeepScore model .m file from my view controller 2, the NSMutableArray objects in KeepScore model .m have reverted to Null values. I made sure my NSMutableArray object values were correct (non Null) right before returning from my KeepScore .m model to my view controller 1. Im working iOS 5.1 with Xcode 4.3.1 with ARC. My NSMutableArray property in my private API declaration in .m model file is strong. Shouldn't the KeepScore model .m keep my array object values when i return to my view controller so that i can use them again when i call my model from my next view controller? I wanted to ask in wording first to see if anyone catches any syupid logic I have. I'll post code if helpful.
Here is my KeepScore.h model
#import
#interface KeepScore : NSObject
- (float)score:(BOOL)questionCorrect:(BOOL)questionTotal:(BOOL)firstScoringPass;
#end
Here is my KeepScore.m model implementation:
#import "KeepScore.h"
#interface KeepScore()
#property (nonatomic, strong) NSMutableArray *correctScoreValues;
#end
#implementation KeepScore
#synthesize correctScoreValues = _correctScoreValues;
- (NSMutableArray *)correctScoreValues
{
if (_correctScoreValues == nil) _correctScoreValues = [[NSMutableArray alloc] init];
return _correctScoreValues;
}
- (float)score:(BOOL)questionCorrect:(BOOL)questionTotal:(BOOL)firstScoringPass {
int totalTried;
int totalCorrect;
NSLog(#"firstScoringPass = %#", firstScoringPass ? #"YES" : #"NO");
NSLog(#"questionCorrect = %#", questionCorrect ? #"YES" : #"NO");
NSLog(#"questionTotal = %#", questionTotal ? #"YES" : #"NO");
if (firstScoringPass) {
int totalTriedInt = 0;
int totalCorrectInt = 0;
NSNumber *correct = [NSNumber numberWithInt:totalCorrectInt];
NSNumber *tried = [NSNumber numberWithInt:totalTriedInt];
[self.correctScoreValues addObject:correct];
[self.correctScoreValues addObject:tried];
firstScoringPass = NO;
}
if (questionCorrect) {
totalCorrect = ([[self.correctScoreValues objectAtIndex:0] intValue] + 1);
NSLog(#"totalCorrect = %d", totalCorrect);
NSNumber *correct = [NSNumber numberWithInt:totalCorrect];
NSLog(#"correct = %#", correct);
[self.correctScoreValues replaceObjectAtIndex:0 withObject:correct];
NSLog(#"correct value in array = %d",[[self.correctScoreValues objectAtIndex:0] intValue]);
} else {
totalCorrect = [[self.correctScoreValues objectAtIndex:0] intValue];
}
NSLog(#"totalCorrect = %d", totalCorrect);
if (questionTotal) {
NSLog(#"tried value in array = %d", [[self.correctScoreValues objectAtIndex:1] intValue]);
totalTried = ([[self.correctScoreValues objectAtIndex:1] intValue] + 1);
NSNumber *tried = [NSNumber numberWithInt:totalTried];
[self.correctScoreValues replaceObjectAtIndex:1 withObject:tried];
NSLog(#"tried value in array = %d", [[self.correctScoreValues objectAtIndex:1] intValue]);
}
float score = (totalCorrect/totalTried);
NSLog(#"score = %0.2f", score);
NSLog(#"totalCorrect = %d, totalTried = %d", totalCorrect, totalTried);
NSLog(#"correct value in array = %d", [[self.correctScoreValues objectAtIndex:0] intValue]);
NSLog(#"tried value in array = %d", [[self.correctScoreValues objectAtIndex:1] intValue]);
return score;
}
#end
Here is one of my ViewControllers .m files:
#import "MapQuizViewController.h"
#import "KeepScore.h"
#interface MapQuizViewController()
#property (nonatomic, strong) KeepScore *scoreModel;
#property (nonatomic) BOOL questionTotal;
#property (nonatomic) BOOL questionCorrect;
#property (nonatomic) BOOL firstScoringPass;
#end
#implementation MapQuizViewController
#synthesize gradeLabel = _gradeLabel;
#synthesize scoreLabel = _scoreLabel;
#synthesize scoreModel = _scoreModel;
#synthesize questionTotal = _questionTotal;
#synthesize questionCorrect = _questionCorrect;
#synthesize firstScoringPass = _firstScoringPass;
- (KeepScore *)scoreModel;
{
if (!_scoreModel) _scoreModel = [[KeepScore alloc] init];
return _scoreModel;
}
- (IBAction)answerButtonPressed:(UIButton *)sender
{
NSString *answerChoice = sender.currentTitle;
NSString *correct = [NSString stringWithFormat:#"Correct!"];
NSString *incorrect = [NSString stringWithFormat:#"Incorrect"];
self.questionTotal = YES;
self.firstScoringPass = YES;
if ([answerChoice isEqualToString:#"Australia"]) {
self.gradeLabel.textColor = [UIColor blueColor];
self.gradeLabel.text = [NSString stringWithFormat:#"%#",correct];
self.questionCorrect = YES;
self.scoreLabel.text = [NSString stringWithFormat:#"%0.2f",[self.scoreModel score:_questionCorrect :_questionTotal :_firstScoringPass]];
} else if ([answerChoice isEqualToString:#"U.S."]) {
self.gradeLabel.textColor = [UIColor redColor];
self.gradeLabel.text = [NSString stringWithFormat:#"%#", incorrect];
self.questionCorrect = NO;
self.scoreLabel.text = [NSString stringWithFormat:#"%0.2f",[self.scoreModel score:_questionCorrect :_questionTotal :_firstScoringPass]];
} else if ([answerChoice isEqualToString:#"China"]) {
self.gradeLabel.textColor = [UIColor redColor];
self.gradeLabel.text = [NSString stringWithFormat:#"%#", incorrect];
self.questionCorrect = NO;
self.scoreLabel.text = [NSString stringWithFormat:#"%0.2f",[self.scoreModel score:_questionCorrect :_questionTotal :_firstScoringPass]];
}
}
- (void)viewDidUnload {
[self setScoreLabel:nil];
[super viewDidUnload];
}
#end
First, a single .m file means nothing. I think you assumed that there is one instance of a Class per .m file which is not true.
for example
// in .m file
static int *myInt; // only one `myInt` exist
// in .h or .m file
#interface MyClass : NSObject {
int myVar; // each MyClass instance will have its own `myVar` which are different
}
// somewhere else
MyClass *a = [[MyClass alloc] init];
MyClass *b = [[MyClass alloc] init];
a->myVar = 1;
b->myVar = 2;
// a->myVar is 1 and b->myVar is 2
If you didn't pass your KeepScore instance around, newly created one will not have previous one's data.
You have to either to make KeepScore singleton or pass it from old view controller to new view controller