3rd view control with NSstring and "Zeros" - iphone

I am having issues with zero's
If my stings contain zeros or nothing the 3rd control view crashed the app.
Any ideas
- (void)viewDidLoad {
appDelegate= (TemplateIponeAppDelegate *)[UIApplication sharedApplication].delegate;
if ([MFMailComposeViewController canSendMail])
mailButton.enabled = YES;
rResults.text = [NSString stringWithFormat:#"R Resultes: %d",appDelegate.RCount];
bResults.text=[NSString stringWithFormat: #"B Resultes: %d",appDelegate.BCount];
pResults.text=[NSString stringWithFormat: #"P Resultes: %d",appDelegate.PCount];
fResults.text=[NSString stringWithFormat: #"F Resultes: %d",appDelegate.FCount];
totalResults.text=[NSString stringWithFormat: #"Total R-P-B: %d",appDelegate.TotalPressed];
rightCount = appDelegate.RCount + appDelegate.BCount+appDelegate.PCount;
grandtotal.text=[NSString stringWithFormat: #"Total : %d",rightCount];
ratiocount= (appDelegate.RCount + appDelegate.BCount+appDelegate.PCount) /appDelegate.FCount;
ratiototal.text = [NSString stringWithFormat: #"Total : %d",appDelegate.FCount];
[super viewDidLoad];

Your problem is this line,
ratiocount= (appDelegate.RCount + appDelegate.BCount+appDelegate.PCount) /appDelegate.FCount;
if appDelegate.FCount is zero, then this will result in an error. You should put some kind of a check on it.

Related

Unable to reload table giving EXC_BAD_ACCESS

while trying to reload table the program giving BAD_EXCESS Signal.
In below code.
-(void)textFieldDidEndEditing:(UITextField *)textField {
NSLog(#"%d",textField.tag);
if (textField.tag == 2) {
IntelligentPillBoxAppDelegate *appdelegate = (IntelligentPillBoxAppDelegate *)[[UIApplication sharedApplication]delegate];
appdelegate.strip1_detail = [pillboxDb get_detail_for_din:value];
[table reloadData];
}
[textField resignFirstResponder];
}
+(NSMutableArray*)get_detail_for_din:(int) din{
NSArray *arrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *strDestPath = [NSString stringWithFormat:#"%#/samplepillbox1.sqlite",[arrDocPath objectAtIndex:0]];
//IntelligentPillBoxAppDelegate *appdelegate = (IntelligentPillBoxAppDelegate *)[[UIApplication sharedApplication]delegate];
//appdelegate.strip1_detail = [[NSMutableArray alloc]init];
NSMutableArray *strip1_detail = [[NSMutableArray alloc]init];
sqlite3 *db;
if(sqlite3_open([strDestPath UTF8String], &db)==SQLITE_OK)
{
NSString *query = [NSString stringWithFormat:#"select * from maintable_master where din =%d ",din];
void* v;
char* err_msg;
sqlite3_stmt *studentStmt;
if(sqlite3_prepare_v2(db, [query UTF8String], -1, &studentStmt, &err_msg)==SQLITE_OK)
{
while (sqlite3_step(studentStmt)==SQLITE_ROW) {
int din = sqlite3_column_int(studentStmt, 0);
NSString *brandname = [NSString stringWithUTF8String: sqlite3_column_text(studentStmt, 1)];
NSString *fullname = [NSString stringWithUTF8String: sqlite3_column_text(studentStmt, 2)];
NSString *strength = [NSString stringWithUTF8String: sqlite3_column_text(studentStmt, 3)];
NSString *medicationtype =[NSString stringWithUTF8String: sqlite3_column_text(studentStmt, 4)];
NSString *presciptionid= [NSString stringWithUTF8String: sqlite3_column_text(studentStmt, 5)];
//float marks = sqlite3_column_double(studentStmt, 2);
//pillbox *st = [[pillbox alloc]init];
//st.Din = sno;
//st.Name = sname;
//NSLog(#"%#",st);
Strip_items *si = [[Strip_items alloc]init];
si.Din = din;
si.BrandName = brandname;
si.FullName = fullname;
si.Strength = strength;
si.MedicationType = medicationtype;
si.PresciptionID = presciptionid;
NSLog(#"%#",si.BrandName);
NSLog(#"%d",si.Din);
NSLog(#"%#",si.FullName);
NSLog(#"%#",si.Strength);
NSLog(#"%#",si.MedicationType);
NSLog(#"%#",si.PresciptionID);
[strip1_detail addObject:si];
}
}
}
return strip1_detail;}
It seems you are not defining all your variables.
Check where value is defined and what its value is.
Also, perhaps you should first resign the responder of the text field and then reload the table view. Depending on your code, the text field whose first responder you resign might not exist any more after a table view reload.
enable zombie objects and it will tell you what error occured.
go to product>edit schems> enabl zombi objects
You are getting BAD_EXCESS in this line...
For more explanation post code of IntelligentPillBoxAppDelegate class
appdelegate.strip1_detail = [pillboxDb get_detail_for_din:value];

How to display x raise to y in UIlabel

how can I display 5 raise to 1/3 in iphone i.e I want 1/3 written above 5 can anyone help please
I Found this solution, hope so it would be helpful for you.
x to the power of y in a UILabel could be easy. Just replace your indices with unicode superscript characters... I use the following method to turn an integer into a string with superscript characters.
+(NSString *)convertIntToSuperscript:(int)i
{
NSArray *array = [[NSArray alloc] initWithObjects:#"⁰", #"¹", #"²", #"³", #"⁴", #"⁵", #"⁶", #"⁷", #"⁸", #"⁹", nil];
if (i >= 0 && i <= 9) {
NSString *myString = [NSString stringWithFormat:#"%#", [array objectAtIndex:i]];
[array release];
return myString;
}
else {
NSString *base = [NSString stringWithFormat:#"%i", i];
NSMutableString *newString = [[NSMutableString alloc] init];
for (int b = 0; b<[base length]; b++) {
int temp = [[base substringWithRange:NSMakeRange(b, 1)] intValue];
[newString appendString:[array objectAtIndex:temp]];
}
[array release];
NSString *returnString = [NSString stringWithString:newString];
[newString release];
return returnString;
}
}
Try this NSString *cmsquare=#"cm\u00B2";
It will display cm².
Yes you can do that but you need custom UILabel, either Make it by yourself or Get it Open Source..

Capture first line of NSString

How do I capture the first line from a NSString object?
I currently am assigning the entire NSString object to the title of my textView, but only want to assign the first line of the string. My current code like this this:
self.textView.text = [[managedObject valueForKey:#"taskText"] description];
You want
self.textView.text = [[[[managedObject valueForKey: #"taskText"] description] componentsSeparatedByString: #"\n"] objectAtIndex:0];
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
If you’re targeting iOS 4.0 and later, you can use -[NSString enumerateLinesUsingBlock:]:
__block NSString *firstLine = nil;
NSString *wholeText = [[managedObject valueForKey:#"taskText"] description];
[wholeText enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
firstLine = [[line retain] autorelease];
*stop = YES;
}];
self.textView.text = firstLine;
An alternative approach which is probably the most efficient and straightforward:
NSString* str = [[managedObject valueForKey:#"taskText"] description];
self.textView.text = [str substringWithRange:[str lineRangeForRange:NSMakeRange(0, 0)]];

How to find the current location in iPhone?

I have written the following code to find the current location.
It works well and prints the current location when I print lat2 and logg2 below in NSLOg, but it is not assigning value to lables. When I print label the value is null.
And I want to access lat2 and logg2 values outside the method didUpdateToLocation.
I am not able to access these values outside the didUpdateToLocation method even though
I have declared logg2 and lat2 globally. Outside this method it gives null value. How can I do that? What is problem here? Is there any sample code or tutorial fot that?
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
-(void)awakeFromNib {
[self update];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (wasFound) return;
wasFound = YES;
CLLocationCoordinate2D loc = [newLocation coordinate];
lat2 = [NSString stringWithFormat: #"%f", loc.latitude];
logg2= [NSString stringWithFormat: #"%f", loc.longitude];
NSLog(#"latitude is %#",lat2);
NSLog(#"longitude is %#",logg2);
NSLog(#"*******This is the login view controller did update locationmethod of loginview controller.");
NSLog(#"latitude is %f",[lat2 floatValue]);
NSLog(#"longitude is %f",[logg2 floatValue]);
labellat.text = [NSString stringWithFormat: #"%f", loc.latitude];
labellog.text= [NSString stringWithFormat: #"%f", loc.longitude];
//NSLog(#"text of label is %#",labellat.text);
//NSLog(#"text of label is %#",labellog.text);
//lat=loc.latitude;
//log=loc.longitude;
//altitude.text = [NSString stringWithFormat: #"%f", newLocation.altitude];
// NSString *mapUrl = [NSString stringWithFormat: #"http://maps.google.com/maps?q=%f,%f", loc.latitude, loc.longitude];
// NSURL *url = [NSURL URLWithString:mapUrl];
// [[UIApplication sharedApplication] openURL:url];
}
- (IBAction)update {
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
NSLog(#"*********This is the location update method of login view controller.");
[locmanager startUpdatingLocation];
}
Basic memory management:
lat2 = [NSString stringWithFormat: #"%f", loc.latitude];
logg2= [NSString stringWithFormat: #"%f", loc.longitude];
These strings are destroyed (deallocated) almost right after you create them. Read up on memory management guidelines. Don't use globals either. If you must, this should fix your strings disappearing:
[lat2 release];
[logg2 release];
lat2 = [[NSString stringWithFormat: #"%f", loc.latitude] retain]; // keep string alive until we release it
logg2= [[NSString stringWithFormat: #"%f", loc.longitude] retain];
Oh, and did you remember to connect the outlets to your labels in Interface Builder?
Use this to show your latitude and longitude in labels.
labellat.text = [NSString stringWithFormat: #"%.6f", loc.latitude];
labellog.text= [NSString stringWithFormat: #"%.6f", loc.longitude];
Please retain the location coordinate to get the values if you want call this from any other places, otherwise it may autorelase.
You can make use of
labellat.text = [NSString stringWithFormat: #"%#", lat2];
labellog.text= [NSString stringWithFormat: #"%#", logg2];
But I think it's better to store the latitude and longitude values as a float itself in an instance variable and thereby getting access to it easily. If you want to show it in a label, use the method stringWithFormat: just as you did.
UPDATE:
The tutorial Hello There: A CoreLocation Tutorial may help you.

Iphone substring causing memory leak

Im just wrapping up my app, so im onto the stage of running instruments to identify leaks in the app. Ive come across a leak that I cannot work out why it is being registered as a leak.
I have the following lines for example:
NSString *imageType = [[[NSString alloc] initWithString:[loopString substringToIndex:[loopString rangeOfString:#"</IMAGE>"].location]] autorelease];
imageType = [imageType substringFromIndex:[imageType rangeOfString:#"<IMAGE>"].location + :#"<IMAGE>".length];
So basically all im doing is pulling out a section of the "loopstring" and putting that into the imagetype string than just cutting off the trailing fluff of the string using the SubstringFromIndex method.
When I run instruments it says "NSCFString substringwithRange" leak. It highlights the second line:
imageType = [imageType substringFromIndex:[imageType rangeOfString:#"<IMAGE>"].location + :#"<IMAGE>".length];
I would think the substringFromIndex method should return a string that is automatically added to the autorelease pool.
Any ideas on where im going wrong?
Thanks
Following is the refactored code:
- (void)SetupTop10:(NSString *)Top10Data
{
while (Top10Data != #"") {
NSLog(Top10Data);
if ([Top10Data rangeOfString:#"</TOP10ENTRY>"].location == NSNotFound){
Top10Data = #"";
}
else
{
NSString *loopString = [Top10Data substringToIndex:[Top10Data rangeOfString:#"</TOP10ENTRY>"].location + 13];
Top10Data = [Top10Data stringByReplacingOccurrencesOfString:loopString withString:#""];
//NOW CREATE A RECORD FOR THIS ITEM
NSString *imageType = [loopString substringToIndex:[loopString rangeOfString:#"</IMAGE>"].location];
imageType = [imageType substringFromIndex:[imageType rangeOfString:#"<IMAGE>"].location + 7];
NSString *displayText = [loopString substringToIndex:[loopString rangeOfString:#"</DISPLAYTEXT>"].location];
displayText = [displayText substringFromIndex:[displayText rangeOfString:#"<DISPLAYTEXT>"].location + 13];
NSString *link = [loopString substringToIndex:[loopString rangeOfString:#"</INTERESTID>"].location];
link = [link substringFromIndex:[link rangeOfString:#"<INTERESTID>"].location + 12];
[Top10Images addObject:imageType];
[Top10Links addObject:link];
[Top10s addObject:displayText];
Top10RowCount = Top10RowCount + 1;
}
}
[self.Top10Table reloadData];
Top10Table.hidden = NO;
loadingLabel.hidden = YES;
loadingIndicator.hidden = YES;
}
//******************
It doesn't look leaky. But why
NSString *imageType = [[[NSString alloc] initWithString:
[loopString substringToIndex:[loopString
rangeOfString:#"</IMAGE>"].location]
] autorelease];
if you effectively get the same with
NSString *imageType = [loopString substringToIndex:[loopString
rangeOfString:#"</IMAGE>"].location];
with half the memory usage?
Leaks will tell you where the leaked memory was allocated. If you click around (there's a right-arrow icon by the memory address, I think) then you can look at all the allocations/retains/releases for that addresses.
In this example, Leaks will point you to the first line, when it's the fifth one that "leaks" (actually it's a missing release in dealloc/on assignment that leaks):
NSString * s = [someString substringFromIndex:1];
[myArray addObject:s];
// ...
NSString * s2 = [myArray lastObject];
instanceVariable = [s2 retain];
// ... and forget to release in dealloc
What does tableView:cellForRowAtIndexPath: do?
I can't see any problem in the above code. Did you release Top10Images in your dealloc method?