Xcode TextField Shows Numbers but Code Adds Decimal - algorithm

I am making tip calculator and this is the code I currently have: (Below). [To make it look nice], is there a way for the user to just put in (15), and have code make that say .15 in the background? Thanks
- (IBAction)calcTapped:(id)sender {
NSString *billAmountString = [billAmountTextField text];
float billAmountFloat = [billAmountString floatValue];
NSString *tipPercentString = [tipPercentTextField text];
float tipPercentFloat = [tipPercentString floatValue];
float tipAmount = billAmountFloat * tipPercentFloat;
NSString *result = [NSString stringWithFormat:#"Tip: %0.2f",
tipAmount];
[resultLabel setText:result];
}

Try retrieving the string from the textfield, converting it into a NSNumber (or float) and then dividing by 100. You know, since 15/100 = 0.15.

Related

Xcode Add (Math) Label and Textfield

Hi I am trying to add (math not put letters together) a textfield's data, and a label's data together. I have preformed the same code you see below for multiplication but when I do the same (A little changed) it does not seem to work. The code I placed below just shows the value of the billAmountTextField. Do you know why? Thanks for your help!
-(IBAction)totalAllUp:(id)sender
{
NSString *billTotalAmountString = [billAmountTextField text];
float billTotalFloat =[billTotalAmountString floatValue];
NSString *tipTotalAmountString = [resultLabel text];
float tipTotalAmountFloat = [tipTotalAmountString floatValue];
float totalAmountAfterAdding = billTotalFloat + tipTotalAmountFloat;
NSString *finalAnswer = [NSString stringWithFormat:#"%0.2f", totalAmountAfterAdding];
[totalAfterAdd setText:finalAnswer];
}

MKmapview - CLLocationCoordinate2D

I have an array NSMutableArray where I save an MKuserlocation type - locationArray.
anyway now I want to get the data from this array and save it to an array from type CLLocationCoordinate2D.
but since everything I save in locationArray is from id type how can I get the coordinates from this and save it to the second array?
CLLocationCoordinate2D* coordRec = malloc(pathLength * sizeof(CLLocationCoordinate2D));
for(id object in locationArray){
for (int i = 0; i < pathLength; i++)
?????
I dont know if this even possible!
Thanks
Why do you need a c-style array of CLLocationCoordinate2D objects?
Here you go:
NSArray* userLocations; // contains your MKUserLocation objects...
CLLocationCoordinate2D* coordinates = malloc( userLocations.count * sizeof( CLLocationCoordinate2D) );
for ( int i = 0 ; i < userLocations.count ; i++ )
{
coordinates[i] = [[[userLocations objectAtIndex: i] location] coordinate];
}
Refering to Apple docs
You should certainly use CLLocationCoordinate2DMake function
with data from MKUserLocation or directly extract infos from MKUserLocation:
object.location.coordinate // it's a CLLocationCoordinate2D from your 'object' example
or
CLLocationCoordinate2DMake(object.location.coordinate.latitude, object.location.coordinate.longitude)
Hope this help.
The typical solution is to create a NSObject subclass and define a single property, a CLLOcationCoordinate2D. Instantiate and add those objects to your array.
#interface Coordinate : NSObject
#property (nonatomic) CLLocationCoordinate2D coordinate;
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate;
#end
#implementation Coordinate
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate
{
self = [super init];
if (self) {
_coordinate = coordinate;
}
return self;
}
#end
And then, because your locationArray is an array of MKUserLocation (which, itself, conforms to MKAnnotation), you can do:
NSMutableArray *path;
path = [NSMutableArray array];
for (id<MKAnnotation> annotation in locationArray)
{
// determine latitude and longitude
[path addObject:[[Coordinate alloc] initWithCoordinate:annotation.coordinate]];
}
Or make an array of existing object type, such as CLLocation or MKPinAnnotation or whatever.
Or if this array is a path to be drawn on the map, you might want to avoid using your own array, and instead make a MKPolyline.
NSInteger pathLength = [locationArray count];
CLLocationCoordinate2D polylineCoordinates[pathLength]; // note, no malloc/free needed
for (NSInteger i = 0; i < pathLength; i++)
{
id<MKAnnotation> annotation = locationArray[i];
polylineCoordinates[i] = annotation.coordinate;
}
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:polylineCoordinates count:pathLength]
[self.mapView addOverlay:polyline];
It depends upon what the purpose of this is. But if you can use one of the previous constructs that avoids malloc and free, that's probably ideal. These techniques leverage Objective-C patterns which make it harder to leak, use an invalid pointer, etc.

How to convert String to double with point?

I'm currently working on an app that works with locations and therefore I have the following code:
CLLocationCoordinate2d coord;
coord.longitude = [longitude doubleValue];
coord.latitide = [latitude doubleValue];
Seems legit, doesn't it?
Now longitude and latitude are STRINGS like "10.112233". I know that normally double hasn't got points in there, but the cllocationcoordinate2d wants it like that...
Now, if you NSLog the strings, they work just fine, but if you NSLog the doubleValues it simply return nothing. How can I fix that?
The following should work:
NSString *coordinateAsString = #"10.112233";
coord.longitude = [[NSDecimalNumber decimalNumberWithString:coordinateAsString] doubleValue];
Can you try using NSDecimalNumber like following:
NSString *string = #"10.112233";
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:string];

route-me image overlay in iPhone

I'm using route-me in my project. Library is quite good. Adding markers, drawing polygone work fine. How about placing single image as overlay in given location (latitude, longitude)? This funcionality is missing I think. Has anyone done placing the image overlay without overloading the tiles source?
I've found the solution...
CLLocationCoordinate2D lcA = CLLocationCoordinate2DMake(oSector.f_overlay_lat_min,oSector.f_overlay_long_min);
CLLocationCoordinate2D lcB = CLLocationCoordinate2DMake(oSector.f_overlay_lat_max,oSector.f_overlay_long_max);
CGPoint cgA = [mvMap latLongToPixel:lcA];
CGPoint cgB = [mvMap latLongToPixel:lcB];
float fLatMin = MIN(cgA.x,cgB.x);
float fLongMin = MIN(cgA.y,cgB.y);
float fWidth = sqrt((cgA.x - cgB.x)*(cgA.x - cgB.x));
float fHeight = sqrt((cgA.y - cgB.y)*(cgA.y - cgB.y));
RMMapLayer *mlLayer = [[RMMapLayer alloc] init];
mlLayer.contents = (id) oSector.im_overlay.CGImage;
mlLayer.frame = CGRectMake(fLatMin,fLongMin,fWidth,fHeight);
[[mvMap.contents overlay] addSublayer:mlLayer];
the mvMap is IBOutlet RMMapView *mvMap somewhere in your h file
the oSector.im_overlay.CGImage can be
UIImage *i = [UIImage imageNamed:<something>];
lmLayer.contents = i.CGImage
Why not just use an RMMarker? You can apply any image you want to it and place it as needed. Even make it draggable if you want to:
UIImage *imgLocation = [UIImage imageWithContentsOfFile :
[[NSBundle mainBundle] pathForResource:#"location_ind"
ofType:#"png"]];
markerCurrentLocation = [[RMMarker alloc] initWithUIImage:imgLocation];
// make sure it is always above everything else.
markerCurrentLocation.zPosition = -1.0;
[mapView.markerManager addMarker:markerCurrentLocation
AtLatLong:startingPoint];
Ciao!
-- Randy

How to create an NSString with one random letter?

I need to create an NSString that has a single random uppercase letter.
I can get random int's fine, and I could construct a C string from it and then make the NSString, but I imagine there has to be a better and more cocoa-ish way.
Thanks!
You can just make an NSString containing what you consider to be letters and pull a random character from it. Here's an example category:
#implementation NSString(RandomLetter)
- (NSString *)randomLetter {
return [self substringWithRange:[self rangeOfComposedCharacterSequenceAtIndex:random()%[self length]]];
}
#end
(You'll need to srandom(time()) at some point, obviously. Maybe include an initialize method in your category.)
I think the best way is to use a c string so that you can use an explicit encoding. Here's an example of that:
NSInteger MyRandomIntegerBetween(NSInteger min, NSInteger max) {
return (random() % (max - min + 1)) + min;
}
NSString *MyStringWithRandomUppercaseLetter(void) {
char string[2] = {0, 0};
string[0] = MyRandomIntegerBetween(65, 90); /// 'A' -> 'Z' in ASCII.
return [[[NSString alloc] initWithCString:string encoding:NSASCIIStringEncoding] autorelease];
}
Here's an alternative, that's really pretty much the same thing, but avoids the C string.
NSString *MyStringWithRandomUppercaseLetter(void) {
unichar letter = MyRandomIntegerBetween(65, 90);
return [[[NSString alloc] initWithCharacters:&letter length:1] autorelease];
}
I prefer the explicit character encodings in the first approach, but they're both correct.

Resources