Passing a user-selected currency into DDUnitConverter - objective-c

I have this code that uses DDUnitConverter for currency conversion.
#import "DDUnitConverter.h"
#import "DDCurrencyUnitConverter.h"
- (void) convertCurrency {
DDUnitConverter *converter = [DDUnitConverter currencyUnitConverter];
NSNumber *from = [NSNumber numberWithInt:42];
NSNumber *to = [converter convertNumber:from fromUnit:DDCurrencyUnitUKPoundSterling toUnit:DDCurrencyUnitUSDollar];
NSLog(#"new value: %#", to);
}
I want to set the fromUnit: and toUnit: arguments based on the user's selection. How should I do that?

DDCurrencyUnit is an enum (enumerated type). If you use a picker view for your user to pick a currency, you can use the selected row index for fromUnit and toUnit, as long as the rows in the picker are in the same order as they are in the enumeration.
For example, DDCurrencyUnitEuro is 0, DDCurrencyUnitJapaneseYen is 1, DDCurrencyUnitUKPoundSterling is 2 and so on. So if the first row of your picker view is "Euro", your second is "Japanese Yen", your third "UK Sterling" and so on, then the selected row index will correspond to the unit parameter.
Your example above is equivalent to
NSNumber *to = [converter convertNumber:from fromUnit:2 toUnit:3];

Related

Numeric UITextField gives a WordNumeral in UILabel

Sorry in advance how I've written this..
In my Main.StoryBoard I have: UITextField (numeric), UILabel and UIButton.
I would like to:
Click UIButton
Take number from UITextField
Give corresponding 'word' and place in UILabel.
Lets say my numbers are in range from 1-9.
I'm having trouble linking the numbers with words and placing into the UILabel.
Is it best to use an NSArray or perhaps a Case Switch?
CODE
int num = [self.stringEntry.text intValue];
THEN... included NSArray of numbers and words correctly.
self.numberOneList = numberOneArray
self.wordOneList = wordOneArray
if (num <= 0 || num >= 10) {
self.wordLabel.text = #"Try a number between 1 and 9";
} else{
// what would I type here?
You can use NSDictionary in this case. Keys can be numbers (0-9) and values can be respected word. Then just take the value from the textfield and check it against the dictionary using valueForKey:.

How to do an on-item-changed for an NSPopUpButton?

I'm trying to implement a system that changes a label based on the state of an NSPopUpButton.
So far I've tried to do what's displayed in the code below, but whenever I run it, the code just jumps into the else clause, throwing an alert
- (IBAction)itemChanged:(id)sender {
if([typePopUp.stringValue isEqualToString: #"Price per character"]) {
_currency = [currencyField stringValue];
[additionalLabel setStringValue: _currency];
}
else if([typePopUp.stringValue isEqualToString: #"Percent saved"]) {
_currency = additionalLabel.stringValue = #"%";
}
else alert(#"Error", #"Please select a calculation type!");
}
So does anyone here know what to do to fix this?
#hamstergene is on the right track, but is comparing the title of the menu item rather than, say, the tag, which is wrong for the following reasons:
It means you cannot internationalize the app.
It introduces the possibility of spelling mistakes.
It's an inefficient comparison; comparing every character in a string takes way longer than comparing a single integer value.
Having said all that, NSPopUpButton makes it difficult to insert tags into the menu items, so you need to use the index of the selected item:
Assume you create the menu items using:
[typePopUp removeAllItems];
[typePopUp addItemsWithTitles: [NSArray arrayWithObjects: #"Choose one...", #"Price per character", #"Percent saved", nil]];
Then create an enum that matches the order of the titles in the array:
typedef enum {
ItemChooseOne,
ItemPricePerCharacter,
ItemPercentSaved
} ItemIndexes;
And then compare the selected item index, as follows:
- (IBAction)itemChanged:(id)sender {
NSInteger index = [(NSPopUpButton *)sender indexOfSelectedItem];
switch (index) {
case ItemChooseOne:
// something here
break;
case ItemPricePerCharacter:
_currency = [currencyField stringValue];
[additionalLabel setStringValue: _currency];
break;
case ItemPercentSaved:
_currency = #"%"; // See NOTE, below
additionalLabel.stringValue = #"%";
break;
default:
alert(#"Error", #"Please select a calculation type!");
}
}
NOTE the following line was incorrect in your code:
_currency = additionalLabel.stringValue = #"%";
Multiple assignment works because the result of x = y is y. This is not the case when a setter is involved. The corrected code is above.
EDIT This answer was heavily edited following more info from the OP.
To query the title of currently selected item in NSPopUpButton:
NSMenuItem* selectedItem = [typePopUp selectedItem];
NSString* selectedItemTitle = [selectedItem title];
if ([selectedItemTitle isEqualTo: ... ]) { ... }
Note that comparing UI strings is a very bad idea. A slightest change in UI will immediately break your code, and you are preventing future localization. You should assign numeric or object values to each item using -[NSMenuItem setTag:] or -[NSMenuItem setRepresentedObject:] and use them to identify items instead.

Programmatically change the state of a UIButton

I've got a pop-up view that loads when a user clicks on a TableView with Core Data elements. On the pop-up view I have a label that represents an int value.
The pop-up view has two butons, one for decreasing the value of the label by 1 and one for increasing it by one. So + and -
What I want to do is to disable the minus button if the label's value is 0. What I've tried is:
-(void)viewDidLayoutSubviews{
NSString *daString = currentVal.text;
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:daString];
int number = [myNumber intValue];
if (number==0)
minus.enabled = NO;
else
minus.enabled = YES
}
The problem with my code is that the button stays disabled after I increase the label's value, and it's no longer equal to 0.
Any suggestions?
You should keep a reference to minus button e.g.
#property (strong, nonatomic) IBOutlet UIButton *minusButton;
Set it with a value of your minus button, or connect outlet in Interface Builder
in your action handler for plusButton, do something like that
-(IBAction)plusAction:(id)sender {
//Do your business logic
...
self.minusButton.enabled = YES;
}
//In your minusButton action handler
-(IBAction)minusAction:(id)sender {
//Do your business logic
...
NSString *daString = currentVal.text;
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:daString];
int number = [myNumber intValue];
if (number==0)
self.minusButton.enabled = NO;
else
self.minusButton.enabled = YES
}
It seems like you have things the other way around. I would take a totally different approach:
Keep an instance variable (which we'll call 'count') in this viewController which holds the number. it can be an NSInteger. now add a target (self) to both buttons with a #selector(buttonPressed:). now this is how this selector should look like:
- (void)buttonPressed:(id)sender{
if (sender==plusButton)
self.count++;
if (sender==minusButton)
self.count--;
label.text = [NSString stringWithFormat:#"%d",self.count];
minusButton.enabled = (self.count>0);
}
I would just do this with a UIStepper, instead of the 2 buttons. You can set properties right in your storyboard/IB file that specify the max and min, increments, and a bunch of other useful things too. There are a couple video tutorials posted on YouTube that probably cover everything you'll need to know to use it.
Also, I have noticed one thing that...
If the button in disabled state and you are trying to change the title of normal state, it wont work.
I had to change the state to enabled and then I could manipulate title and set back to disabled.

Set color of UITextfield based on numeric value using an If-statement in Objective-C

I currently use a UIStepper in a custom UITableViewCell hooked up to a UITextField to have people select how many items they want to add to their Shopping Cart.
To check if the object is in stock, I've got two numbers: The LocalStock and the TotalStock.
I want to do the following:
If the amount of objects falls into the local stock, I want the textfield the number is displayed in to turn green.
If the amount of objects falls into the supplier stock (so either there is no local stock, or the stepper value is higher than the local stock, so we need to get it from the supplier stock) turn the UITextField blue.
If neither the supplier stock nor local stock are sufficient, I want the textfield to turn yellow.
I got the following code:
- (IBAction)stepperValueChanged:(id)sender
NSLog(#"localstock: %#",localstock);
NSLog(#"TotalStock: %#",totalstock);
NSDecimalNumber *value = [NSDecimalNumber decimalNumberWithString: self.textField.text];
if (value <= localstock)
{
self.aantalTextField.backgroundColor = [UIColor greenColor];
NSLog(#"Value %# <= Localstock %# >GREEN< Totalstock: %#",value,localstock, totalstock);
}
else if (value <= totalstock)
{
self.aantalTextField.backgroundColor = [UIColor blueColor];
NSLog(#"Value %# <= totalstock %# >BLUE< Localstock: %#",value,totalstock,localstock);
}
else
{
self.aantalTextField.backgroundColor = [UIColor yellowColor];
NSLog(#"Value: %# LocalStock: %# TotalStock %# >YELLOW<",value,localstock,totalstock);}}
And it's not making much sense when I run it... Sometimes it catches the GREEN-statement, other times the BLUE, and sometimes the same value returns YELLOW.
Anyone care to take a look at this and show me where the (logical) error is?
Thanks in advance!
You are comparing objects, not their values. As long they are both of type NSDecimalNumber...you need to compare similar to this.
[value integerValue ] <= [localstock integerValue]
As far as I understood from your code, localstock, totalstock and value are objects, not integers and you are comparing objects pointers, not values.
Instead, you should use the
- (NSComparisonResult)compare:(NSNumber *)decimalNumber
declared in NSDecimalNumber class.
Or convert all to integers using for example
[value intValue]

Tableview cells does not display data when in integer format

My application has a sqlite database and i m using executeQuery methods to retrive and insert data.
Problem
I cannot assign integer values cells of tableview. It does not display data which is in integer format. i want to store integer values into a tableview and show sorted integer
data to user.
Here i am posting my code
1) in viewDidLoad i have retrieved integer values from database table "dummy" and taken it into an NSArray "Scores"
2) i have assigned a value of "highscore" which is an integer type to cell in "cellForRowAtIndexPath" Method of table view.Note that converting this data into NSString does not allow sorting.
But this shows no data in table cells when i run it.
1)
NSString *myDBnew = #"/Users/taxsmart/Documents/sqlite/atest.sql";
database = [[Sqlite alloc] init];
[database open:myDBnew];
Scores = [database executeQuery:#"SELECT * FROM dummy ORDER BY highscore DESC;"];
2)
cell.textLabel.text = [[Scores objectAtIndex:indexPath.row] valueForKey:#"highscore"];
What is Wrong?
Please Give Your Suggestions. Your Suggestions are most welcome.
You must assign an NSString* to cell.textLabel.text. Just embedd your ints into an NSString.
NSInteger highscore = [[Scores objectAtIndex:indexPath.row] valueForKey:#"highscore"];
cell.textLabel.text = [NSString stringWithFormat:#"%d", highscore];