Multiple NSObject Initialization Causes code to stop executing - ios

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.

Related

Custom Class sort property with NSDate not working in Objective-C

I create the custom class name with FileModel.
FileModel.h
#import <Foundation/Foundation.h>
#interface FileModel : NSObject
#property (nonatomic, copy) NSString *fileName;
#property (nonatomic, copy) NSString *fileType;
#property (nonatomic, strong) NSDate *editDate;
#property (nonatomic, assign) NSInteger fileSize;
#end
I want to sort the FileModel with the editDate, but it is not work.
I create the sample like below .m
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *fileSampleName = [[NSArray alloc] initWithObjects:#"apple.png",#"banana.png",#"cherry.png",#"durian.png",#"grape.png",#"avocado.png", nil];
NSMutableArray *fileData = [NSMutableArray new];
FileModel *fileModel = nil;
for( NSInteger i = 0 ; i < fileSampleName.count ; i++){
fileModel = [FileModel new];
fileModel.fileName = [fileSampleName objectAtIndex:i];
fileModel.fileType = #"photo";
fileModel.fileSize = 0;
fileModel.editDate = [NSDate new];
[fileData addObject:fileModel];
// test for nsdate interveral
[NSThread sleepForTimeInterval:1];
}
NSArray *sortedArray;
sortedArray = [fileData sortedArrayUsingComparator:^NSComparisonResult(FileModel *a, FileModel *b) {
NSDate *first = [(FileModel*)a editDate];
NSDate *second = [(FileModel*)a editDate];
return [second compare:first];
}];
NSLog(#"sortedArray:%#",sortedArray);
// log
for (FileModel *fm in sortedArray) {
NSLog(#"sortedArray:%#", fm.fileName);
}
}
Why I NSLog sorted order is not
avocado.png -> grape.png -> durian.png -> cherry.png -> banana.png ->
apple.png
Thank you very much.
You miss typed a again instead of b in second variable
NSArray *sortedArray;
sortedArray = [fileData sortedArrayUsingComparator:^NSComparisonResult(FileModel *a, FileModel *b) {
NSDate *first = [(FileModel*)a editDate];
NSDate *second = [(FileModel*)b editDate];
return [second compare: first];
}];
Try this
NSArray *sortArray = [fileData sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSDate *first = [(FileModal*)obj1 editDate];
NSDate *second = [(FileModal*)obj2 editDate];
return !([first compare:second] == NSOrderedDescending);
}];

Why isn't my UILabel getting set? [closed]

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

Save large NSDictionary to disk iOS

My application is designed to view the catalog with products. All data received from the server (xml) are parsed in NSDictionary. So NSDictionary contains about 5000 items. Reading a dictionary using NSKeyedUnarchiver takes 24 seconds. It is unacceptable.
I don't need forward and backward compatible, because after app updating catalog will be downloaded again and old data will be deleted.
My dictionary isn't property list, so writeToFile isn't working.
NSArchiever(NSUnarchiever) would be a great solution to the problem, but it replaced by NSKeyedArchiver.
Any ideas? Maybe I should use CoreData but I don't know anything about it.
Thanks
Have you tried saving it as a JSON formatted file? NSJSONSerialization would help you go back and forth between file data and a NSDictionary. It was added in iOS5.
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
Let me know if it performs well enough for you.
My solution is to use custom serialization. In the end, all data is presented as property list. All my custom classes that should be serialized support protocol PropertyListCoder (like NSCoder):
#protocol PropertyListCoder
- (id)encodeToPropertyListObject;
- (id)initWithPropertyListObject:(id)object;
#end
For example, serialization for class Product:
#interface Product : NamedObject <NSCoding, PropertyListCoder> {
}
#property (nonatomic, readwrite) uint mId;
#property (nonatomic, retain) NSString *mDesc;
#property (nonatomic, retain) NSString *mIcon;
#property (nonatomic, retain) NSString *mCode;
#property (nonatomic, readwrite) uint mSort;
#property (nonatomic, retain) NSMutableArray *mArrOfText;
#property (nonatomic, readonly) NSMutableArray *mProperties;
#property (nonatomic, retain) NSString *mImage;
#property (nonatomic, readwrite) float mPrice;
#property (nonatomic, readwrite) float mDiscPrice;
#end
And here are methods of the protocol:
- (id)encodeToPropertyListObject {
id superPropList = [super encodeToPropertyListObject];
NSNumber* idNumber = [[NSNumber alloc] initWithInt:mId];
NSNumber* sortNumber = [[NSNumber alloc] initWithInt:mSort];
NSMutableArray* arrOfTextPropList = [[NSMutableArray alloc] init];
for (NSAttString* str in self.mArrOfText) {
[arrOfTextPropList addObject:[str encodeToPropertyListObject]];
}
NSMutableArray* propPropList = [[NSMutableArray alloc] init];
for (Property* prop in self.mProperties) {
[propPropList addObject:[prop encodeToPropertyListObject]];
}
NSNumber* priceNumber = [[NSNumber alloc] initWithInt:mPrice];
NSNumber* discPriceNumber = [[NSNumber alloc] initWithInt:mDiscPrice];
NSArray* res = [NSArray arrayWithObjects:superPropList, idNumber, [Utility notNilStringWithString:mDesc], [Utility notNilStringWithString:mIcon], [Utility notNilStringWithString:mCode], sortNumber, arrOfTextPropList, propPropList, [Utility notNilStringWithString:mImage], priceNumber, discPriceNumber, nil];
[idNumber release];
[sortNumber release];
[arrOfTextPropList release];
[propPropList release];
[priceNumber release];
[discPriceNumber release];
return res;
}
- (id)initWithPropertyListObject:(id)object {
NSArray* arr = (NSArray*)object;
self = [super initWithPropertyListObject:[arr objectAtIndex:0]];
if (self) {
mId = [[arr objectAtIndex:1] intValue];
mDesc = [[arr objectAtIndex:2] retain];
mIcon = [[arr objectAtIndex:3] retain];
mCode = [[arr objectAtIndex:4] retain];
mSort = [[arr objectAtIndex:5] intValue];
mArrOfText = [[NSMutableArray alloc] init];
mProperties = [[NSMutableArray alloc] init];
for (id subObj in (NSArray*)[arr objectAtIndex:6]) {
NSAttString* str = [[NSAttString alloc] initWithPropertyListObject:subObj];
[mArrOfText addObject:str];
[str release];
}
for (id subObj in (NSArray*)[arr objectAtIndex:7]) {
Property* prop = [[Property alloc] initWithPropertyListObject:subObj];
[mProperties addObject:prop];
[prop release];
}
mImage = [[arr objectAtIndex:8] retain];
mPrice = [[arr objectAtIndex:9] floatValue];
mDiscPrice = [[arr objectAtIndex:10] floatValue];
}
return self;
}
Root object could be NSDictionary or NSArray. Then for read / write I use NSPropertyListSerialization with binary format.
And now reading the dictionary takes 3.5 seconds!

Displaying Integer value in a Label , int to String conversion?

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;

NSMutableArray object values not being retained when returning from my model .m file

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

Resources