IBAction float, have a equal different numbers depending on input - xcode

New to objective-c and I just can't find the answer to this question anywhere. I'm running a IBAction for a calculation but I need the input from a label to actually equal something else in the equation.
For example:
-(IBAction)calculate; {
float a = 1.05 if ([label1.text] == 1in);
a = 2.07 if ([label1.text] == 2in);
a = 3.07 if ([label1.text] == 3in);
float b = a*([textField1.text floatValue]);
label2.text = [[NSString alloc] initWithFormat:#"%2.f", b];
}
I know I'm not even close to getting it right but I hope you get the idea as to what I'm looking for.
Thank you!

- (void)calculate {
float a;
if ([self.inputField.text isEqualToString:#"1in"]) a = 1.05f;
else if ([self.inputField.text isEqualToString:#"2in"]) a = 2.07f;
else if ([self.inputField.text isEqualToString:#"3in"]) a = 3.07f;
else a = 0.0f;
if (a) {
float b = a * ([self.inputField.text floatValue]);
self.inputField.text = [[NSString alloc] initWithFormat:#"%.2f", b];
}
else self.inputField.text = #"Invalid";
}
- (void)viewDidLoad
{
//...
self.inputField = [[UITextField alloc] initWithFrame:CGRectMake(10.0f, 20.0f, 300.0f, 30.0f)];
[self.inputField setBackgroundColor:[UIColor grayColor]];
[self.view addSubview:self.inputField];
UIButton * doneButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, 55.0f, 300.0f, 30.0f)];
[doneButton setBackgroundColor:[UIColor blackColor]];
[doneButton setTitle:#"Done" forState:UIControlStateNormal];
[doneButton addTarget:self action:#selector(calculate) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:doneButton];
[doneButton release];
}
Note: I replaced the output format %2.f to %.2f, cause I guess you may need this format. E.g:
Input > 1in
Output< 1.05
Input > 2in
Output< 4.14
Input > 3in
Output< 9.21

Related

AVSpeechSynthesizer - How to detect dot for milliseconds pause (iPHONE - iPAD / iOS7 xcode)

I want to read a very long text:
NSString *text =#"Long test with dot. I want speaching pause when read dot. How can I do?";
AVSpeechSynthesizer *synthesizer = [AVSpeechSynthesizer new];
[synthesizer setDelegate:self];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:text];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:[self.defaults objectForKey:LANGUAGE]];
utterance.rate = 0.28;
[synthesizer speakUtterance:utterance];
I want synthesizer detect dot and pause for 100 millisecond.
Is it possible? How can I do ??
I mean a dot (.)
but maybe I found a solution also fot char ',' :
NSString *text = #"Line one. LineTwo aftre a pause. Line three, pause here again.";
text = [text stringByReplacingOccurrencesOfString:#"," withString:#"."];
NSArray *a = [text componentsSeparatedByString:#"."];
for(NSString *line in a)
{
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:line];
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:[self.defaults objectForKey:LINGUA]];
utterance.rate = 0.28;
utterance.**postUtteranceDelay** = 0.3;
[self.synthesizer speakUtterance:utterance];
}

Multiplying double variable by double in Xcode

I'm making in app that includes a user entering the price of an object, and the app outputs the price including tax. However, every time it outputs 0, and I get a run-time error involving the variable, myDouble. I'm trying to take the value put in a text field and multiplying it by 1.06 (I'm starting out with a set tax rate), and then setting a label to the new value. Here is my code:
-(IBAction)textFieldReturn:(id)sender
{
[sender resignFirstResponder];
NSString *myString = inputtext2.text;
double myDouble = [myString doubleValue];
myDouble = myDouble*1.06;
NSLog(#"myDouble: %lf", myDouble);
price.text = [NSString stringWithFormat:#"%g", myDouble];
}
Most likely your inputtext2 variable is nil, so it is returning nothing. If this is an outlet, check the connections in interface builder. If the outlet is not connected, the variable will be nil, so the string value will be nil, so the double value will be 0.
I think you are going to want to use a NSNumberFormatter and check for valid entry.
pseudo code, uncompiled:
-(IBAction)textFieldReturn:(id)sender
{
[sender resignFirstResponder];
NSString *myString = inputtext2.text;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle: NSNumberFormatterDecimalStyle];
NSNumber *myNumber = [formatter numberFromString: myString];
double myDouble = 0;
if (myNumber != nil) {
myDouble = [myNumber doubleValue];
}
NSString *outputString = [formatter stringFromNumber:myDouble];
price.text = outputString;
}
This should default your number to 0 if the text entered is 0 or not a valid number.

Sort by Double Value and not String Value

I'm currently pulling info from an sql DB where the 'cachedDist' column is set as a double. However when I pull it into my app and create my array I turn it into an String and the sort will obviously be off, 18.15 will come before 2.15. How do I fix that in my code so it will sort distance as a Double and not a String?
In Bar object.
NSString *cachedDist
#property(nonatomic,copy) NSString *cachedDist;
#synthesize cachedDist;
My while loop in the View Controller.
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Bar * bar = [[Bar alloc] init];
bar.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
bar.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
bar.barCity = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)];
bar.barState = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)];
bar.barZip = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)];
bar.barLat = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)];
bar.barLong = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)];
if (currentLoc == nil) {
NSLog(#"current location is nil %#", currentLoc);
}else{
CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[bar.barLat doubleValue] longitude:[bar.barLong doubleValue]];
bar.cachedDist = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000];
[thebars addObject:bar];
}
My sorting
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"cachedDist" ascending:YES];
sortedArray = [thebars sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
return sortedArray;
NSString has a method doubleValue to make this quite simple:
double cachedDistance = [cachedDistanceString doubleValue];
which you can use in a custom comparator for your sorting, or else make the property an NSNumber or double to make sorting that much easier. (I'm not sure how you are sorting...)
edit:
I re-evaluated your code, and now it looks like we are going from a double to a string to a double... we can cut out the middle-man, so to speak.
In your #prototype section, change the #property:
// #property(nonatomic,copy) NSString *cachedDist; // old way
#property(nonatomic) double cachedDist;
then assign it like this:
bar.cachedDistance = [currentLoc distanceFromLocation: barLocation]/1000;
and remove the lines which create a string from the distance (which is actually just a double).
Alternatively, if you want to be more object oriented, you can (should?) use NSNumber objects:
#property(nonatomic,copy) NSNumber *cachedDist;
...
bar.cachedDistance = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000];

How do i get the range of the current paragraph in a NSTextView where the cussor stayed there?

Now i need to change the alignment of a paragraph in a nstextview without select it ,so i need to know the range of the current range of the paragraph?
I have a subclass of NSTextView so you need to access textStorage and selectedRange different than [self textStorage] and [self selectedRange].
NSTextStorage *textStorage = [self textStorage];
NSString *string = [textStorage string];
NSUInteger editEnd = [self selectedRange].location;
NSUInteger editStart = editEnd-[textStorage editedRange].length;
NSUInteger maxLength = [string length];
while (editStart > 0) {
unichar theChr = [string characterAtIndex:editStart-1];
if( theChr == '\n' || theChr == '\r' ) {
break;
}
--editStart;
}
while (editEnd < maxLength) {
unichar theChr = [string characterAtIndex:editEnd];
if( theChr == '\n' || theChr == '\r' ) {
break;
}
++editEnd;
}
NSRange paragraphRange = NSMakeRange(editStart, editEnd-editStart);
Here's a shortcut:
NSRange paragraphRange = [textView.textStorage.string paragraphRangeForRange: [textView selectedRange]];
First, get the range where the cursor stayed through [textView selectedRange]
Then you can get the line range through - (NSRange)lineRangeForRange:(NSRange)range of [textView string]
Here is a example code:
NSRange sel = [textView selectedRange];
NSString *viewContent = [textView string];
NSRange lineRange = [viewContent lineRangeForRange:NSMakeRange(sel.location,0)];
detail in there.
How to get the selected line range of NSTextView?

What kind of category methods do you use to make Cocoa programming easier?

I use a collection of category methods for Cocoa's built in classes to make my life easier. I'll post some examples, but I really want to see what other coders have come up with. What kind of handy category methods are you using?
Example #1:
#implementation NSColor (MyCategories)
+ (NSColor *)colorWithCode:(long)code
{
return [NSColor colorWithCalibratedRed:((code & 0xFF000000) >> 24) / 255.0
green:((code & 0x00FF0000) >> 16) / 255.0
blue:((code & 0x0000FF00) >> 8) / 255.0
alpha:((code & 0x000000FF) ) / 255.0];
}
#end
// usage:
NSColor * someColor = [NSColor colorWithCode:0xABCDEFFF];
Example #2:
#implementation NSView (MyCategories)
- (id)addNewSubViewOfType:(Class)viewType inFrame:(NSRect)frame
{
id newView = [[viewType alloc] initWithFrame:frame];
[self addSubview:newView];
return [newView autorelease];
}
#end
// usage:
NSButton * myButton = [someView addNewSubviewOfType:[NSButton class]
inFrame:someRect];
I've really been loving Andy Matuschak's "KVO+Blocks" category on NSObject. (Yes, it adds some new classes internally as implementation details, but the end result is just a category on NSObject). It lets you provide a block to be executed when a KVO-conforming value changes rather than having to handle every KVO observation in the observeValueForKeyPath:ofObject:change:context: method.
Regular Expressions with RegexKitLite. Download # RegexKitLite-3.1.tar.bz2
Category, which adds md5/sha1 hashing to NSString. NSData one is similar.
#define COMMON_DIGEST_FOR_OPENSSL
#import <CommonCrypto/CommonDigest.h>
#implementation NSString(GNExtensions)
- (NSString*)
hashMD5
{
NSData* data = [self dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion: NO];
unsigned char hashingBuffer[16];
char outputBuffer[32];
CC_MD5([data bytes], [data length], hashingBuffer);
for(int index = 0; index < 16; index++)
{
sprintf(&outputBuffer[2 * index], "%02x", hashingBuffer[index]);
}
return([NSString stringWithCString: outputBuffer length: 32]);
}
- (NSString*)
hashSHA1
{
NSData* data = [self dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion: NO];
unsigned char hashingBuffer[20];
char outputBuffer[40];
CC_SHA1([data bytes], [data length], hashingBuffer);
for(int index = 0; index < 20; index++)
{
sprintf(&outputBuffer[2 * index], "%02x", hashingBuffer[index]);
}
return([NSString stringWithCString: outputBuffer length: 40]);
}
#end
I have a few nifty methods on NSDate. This is self-explanatory:
-(BOOL)isOnTheSameDayAsDate:(NSDate *)date {
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *selfComponents = [cal components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:self];
NSDateComponents *dateComponents = [cal components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
fromDate:date];
return (([selfComponents day] == [dateComponents day]) &&
([selfComponents month] == [dateComponents month]) &&
([selfComponents year] == [dateComponents year]));
}
Usage:
if ([aDate isOnTheSameDayAsDate:anotherDate]) { ... }
This provides a method to easily get dates like "9am the day before":
-(NSDate *)dateWithDayDelta:(NSInteger)daysBeforeOrAfter atHour:(NSUInteger)hour minute:(NSUInteger)minute second:(NSUInteger)second {
NSDate *date = [self addTimeInterval:(24 * 60 * 60) * daysBeforeOrAfter];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit |
NSMinuteCalendarUnit | NSSecondCalendarUnit
fromDate:date];
[comps setHour:hour];
[comps setMinute:minute];
[comps setSecond:second];
return [calendar dateFromComponents:comps];
}
Usage:
// We want 9am yesterday
NSDate *nineAmYesterday = [[NSDate date] dateWithDayDelta:-1
atHour:9
minute:0
second:0];

Resources