NSRange not matching with NSNotFound - objective-c

I have the following method:
- (IBAction)digitPressed:(UIButton *)sender {
NSLog(#"%#", sender.currentTitle);
if (self.userTypingNumber) {
if (![sender.currentTitle isEqualToString:#"."])
self.display.text = [self.display.text stringByAppendingString:sender.currentTitle];
else {
NSRange range = [sender.currentTitle rangeOfString:#"."];
if (range.location == NSNotFound) {
self.display.text = [self.display.text stringByAppendingString:sender.currentTitle];
}
}
} else {
self.display.text = sender.currentTitle;
self.userTypingNumber = YES;
}
}
My problem is that my program never enters de NSNotFound if. I'm making a calculator and it should accept floating point numbers, but whenever I press the . it just passes right over the if. Any idea what could be wrong?

Looking at your logic, sender.currentTitle is always going to be #"." in your else statement, and so your range is always going to have a location of 0.

Related

Always returning null in NSString return function

I have the following code where I want to convert decimal odds to fractional odds. However the function findNearestWholeInteger always returns null.
- (NSString *)displayOddWithFormat:(NSString *)decimalOdd {
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"FractionalOdds"] == YES) {
float oddsF = decimalOdd.floatValue;
oddsF = oddsF - 1.0f;
return [self findNearestWholeInteger:oddsF andInitial:oddsF andBottom:1];
} else {
return odd;
}
}
- (NSString *)findNearestWholeInteger:(float)odds andInitial:(float)initial andBottom:(float)bottom {
NSNumber *numberValue = [NSNumber numberWithFloat:odds];
NSString *floatString = [numberValue stringValue];
NSArray *floatStringComps = [floatString componentsSeparatedByString:#"."];
if (floatStringComps.count == 1) {
return [NSString stringWithFormat:#"%.f/%.f", odds, bottom];
} else {
bottom += 1;
odds += initial;
[self findNearestWholeInteger:odds andInitial:initial andBottom:bottom];
return nil;
}
}
Any ideas where I need to adapt my code? Thanks in advance!
Don't you want:
return [self findNearestWholeInteger:odds andInitial:initial andBottom:bottom];
//return nil;
(not that I really understand what the method is doing).

Can't get negative sign in calculator to disappear

I'm working on an iOS 5 calculator that contains the following code:
- (IBAction)digitPressed:(UIButton *)sender
{
//Enter digit, avoiding two-decimal-point case.
NSString *digit = sender.currentTitle;
NSRange range = [self.display.text rangeOfString:#"."];
if (range.location==NSNotFound || (![digit isEqualToString:#"."]))
if (self.userIsEnteringNumber)
{
self.display.text = [self.display.text stringByAppendingString:digit];
}
else
{
if (![sender.currentTitle isEqualToString:#"."])
{
self.display.text = digit;
}
else
{
self.display.text = #"0.";
}
self.userIsEnteringNumber = YES;
}
}
and
- (IBAction)changeSignPressed
{
//Reverse sign from positive to negative or vice versa.
if (self.numberIsNegative) self.numberIsNegative = NO;
if (!(self.numberIsNegative)) self.numberIsNegative = YES;
//Correct display to reflect change in sign.
if (self.numberIsNegative)
{
if (![[self.display.text substringToIndex:1] isEqualToString:#"-"])
{
self.display.text = [#"-" stringByAppendingString:self.display.text];
}
}
if (!self.numberIsNegative)
{
/*This isn't working--why not?
if ([[self.display.text substringToIndex:1] isEqualToString:#"-"])
{
NSLog(#"Okay."); //This doesn't log, so obv. the problem is in the previous line.
self.display.text = [self.display.text substringFromIndex:1];
}
*/
}
}
I can't get the commented-out code in changeSignPressed to work no matter how I fiddle with it. Any ideas about how I can fix this?
It's probably this code:
//Reverse sign from positive to negative or vice versa.
if (self.numberIsNegative) self.numberIsNegative = NO;
if (!(self.numberIsNegative)) self.numberIsNegative = YES;
There is no else so if self.numberIsNegative is initially YES it will become NO; it will then be immediately seen as NO on the following line where it is changed back to YES.
In any case, that code is more complex than it needs to be; you can just say this to invert a flag:
self.numberIsNegative = ! self.numberIsNegative;

search method not working after second hit

I've a problem with my UISearchDisplayController, the search is not working properly.
This is my code:
- (void)filterContentForSearchText:(NSString*)searchText
scope:(NSString*)scope
{
[self.searchResults removeAllObjects];
for (int i = 0; i < [temp_category count]; i++) {
BOOL foundResult = FALSE;
if ([[temp_category objectAtIndex:i] rangeOfString:searchText].location != NSNotFound) {
foundResult = TRUE;
}
if ([[price_producttitle objectAtIndex:i] rangeOfString:searchText].location != NSNotFound) {
foundResult = TRUE;
}
if ([[price_type objectAtIndex:i] rangeOfString:searchText].location != NSNotFound) {
foundResult = TRUE;
}
if ([[price_description objectAtIndex:i] rangeOfString:searchText].location != NSNotFound) {
foundResult = TRUE;
}
if (foundResult) {
NSNumber *result = [NSNumber numberWithInt:i];
if ([self searchResults] == nil) {
NSMutableArray *array = [[NSMutableArray alloc] init];
[self setSearchResults:array];
[array release];
}
[searchResults addObject:result];
}
}
NSLog (#"array = %i", [searchResults count]);
NSLog(#"%#",searchResults);
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:[self.searchDisplayController.searchBar text]
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:searchOption]];
return YES;
}
But I'm still confused, because when I start a search with the first letter, it gives the correct hits. But when I enter the second letter, it only shows one result (while there are more, as far as I know from my data sample). I'm doing something incorrectly. I think it has something to do with when the user enters text, but I'm confused which method I should use.
The code I now have is a combination of:
this tutorial and
this SO question.
Can someone give me a hint in the good direction? Displaying the results is fine, only this aspect bothers me. I think it has something to do with firing the method and [self.searchResults removeAllObjects];.
I would like to add my code, but the thing is that I still use the code I have above, but I'm manually implementing the UISearchBar (which I found somewhere else in a tutorial) instead of using SearchDisplayController. I also had difficulties with the navigationbar which dissappears when using SearchDisplayController, which gave me enough reason to implement it myself instead of using SearchDisplayController. It gives you more freedom.
At first it seemed a lot of work, so I choose to use SearchDisplayController, but I really advise anyone who needs some modification, or who wants more freedom, please do it manually with UISearchBar and a UITableView :)

CS193P - Adding floating point button to iOS calculator

I recently started following the online course on iPhone development from Stanford University on iTunes U.
I'm trying to do the homework assignments now for the first couple of lectures. I followed through the walkthrough where I built a basic calculator, but now I'm trying the first assignment and I can't seem to work it out. It's a follows:
Your calculator already works with floating point numbers (e.g. if you press 3 / 4 =
it will properly show the resulting value of 0.75), however, there is no way for the user
to enter a floating point number. Remedy this. Allow only legal floating point
numbers to be entered (e.g. “192.168.0.1” is not a legal floating point number).
First of all, I'm not sure whether a floating point counts as digitPressed or operationPressed. I even tried with a new method called floatingPointPressed but that didn't really work out. Could someone provide pointers on this?
When I saw it as digitPressed, I tried something like this:
if (hasFloatingPoint) {
NSRange range = [[display text] rangeOfString:#"."];
if (range.location == NSNotFound)
{
[display setText:[[display text] stringByAppendingFormat:digit]];
hasFloatingPoint = YES;
}
}
else {
[display setText:[[display text] stringByAppendingFormat:digit]];
}
But I'm missing the key concept here, I think.
I have also tried another solution which I have, sadly, undone already so I can't provide the code but what happend was this: I could press a number, say 5 and then a floating point and 3 so I would end up with 5.3. I then managed to 'disable' the floating point for the remainder of the input.. But I guess I was a little too strict on it: I couldn't, for example, put in 5.3.2 but after pressing an operation button (+, etc), it still wouldn't let me press the floating point button. I guess I should reset the bool I used for this?
I'm not looking for a completely written out solution here, but could someone be so kind to provide some basic advice on how to tackle this problem? Some kind of step-by-step overview of what I should do and think about, without actually providing a code solution.
Thanks in advance.
Okay. I solved this. Was fairly easy once I managed to wrap my head around it:
-(IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [[sender titleLabel] text];
NSRange range = [[display text] rangeOfString:#"."];
if (userIsInTheMiddleOfTypingANumber)
{
if ( ! ([digit isEqual:#"."] && (range.location != NSNotFound))) {
[display setText:[[display text] stringByAppendingFormat:digit]];
}
}
else
{
if ([digit isEqual:#"."]) {
[display setText: #"0."];
}
else {
[display setText: digit];
}
userIsInTheMiddleOfTypingANumber = YES;
}
}
Since you want a hint of where to look, have a look at attaching a NSNumberFormatter to the input fields.
This is the proper way of validating input, rather than manually checking each character the user enters yourself.
edit
I've just read the assignment that you are trying to work through. I think my answer here, although still the right way to do it, not the best way to do what the assignment is trying to get you to do.
Since you are reading the digits one by one as they are added to the view and appending them to the number you are operating on you may be on the right track with your original answer:
Keep accepting numbers as they are added
Add a decimalEntered flag - initialise it to 'NO'
If a decimal is entered, check the flag, if it is no, accept it and set the flag to YES
If a decimal is entered and the flag is YES, don't accept it.
Whenever you press an operand, set this flag back to NO.
When you learn a bit more, you'll realise that another way to do this is to let the user type in the field. Hook up a formatter to the field to validate that the input is a valid number, but it will also be able to turn the string into a number for you. And when an operand is pressed, this number will be kept aside as one of the numbers upon which the operand will operate.
-(IBAction)floatingPoint:(UIButton *)sender {
NSString *digit = sender.currentTitle;
NSRange range = [self.display.text rangeOfString:#"."];
if(range.location == NSNotFound){
self.display.text = [self.display.text stringByAppendingString:digit];
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
Your can also use scanners to solve this problem. The code is simpler and I think it also localized.
if (userIsInTheMiddleOfTypingANumber) {
// Allow floating point numbers to be input. Malformed numbers are replaced by 0
NSScanner *scanner = [NSScanner scannerWithString:display.text];
double d;
BOOL wellFormedDouble = [scanner scanDouble:&d];
if (wellFormedDouble && [scanner isAtEnd]) {
brain.operand=d;
}
else {
brain.operand=0;
}
userIsInTheMiddleOfTypingANumber = NO;
}
Hey I think I have a simple solution that works :)
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [[sender titleLabel] text];
NSRange range = [[display text] rangeOfString:#"."];
if (range.location != NSNotFound && [digit isEqual:#"."]) {
return;
}
if (userIsInTheMiddleOfTypingANumber)
{
[display setText:[[display text] stringByAppendingString:digit]];
}
else
{
[display setText:[digit isEqual:#"."] ? #"0." : digit];
userIsInTheMiddleOfTypingANumber = YES;
}
}
i saw that it suggests to add a function to handle the decimal after i started in on that bit, and ended up with this. the decimal flag is reset in operation pressed. and to really complete it, it should probably disallow leading 0's too.
if (userIsInTheMiddleOfTypingANumber) {
if ([digit isEqual:#"."]) {
if (!userIsInTheMiddleOfTypingADecimal) {
[display setText:[[display text] stringByAppendingString:digit]];
userIsInTheMiddleOfTypingADecimal = YES;
}
}else {
[display setText:[[display text] stringByAppendingString:digit]];
}
}
else//new number
{
if ([digit isEqual:#"."]) {
if (!userIsInTheMiddleOfTypingADecimal) {// this is a superfluous check as if it's a new number it is also not a decimal.
[display setText:#"0."];
userIsInTheMiddleOfTypingADecimal = YES;
userIsInTheMiddleOfTypingANumber = YES;
}
}else {
[display setText:digit];
userIsInTheMiddleOfTypingANumber = YES;
}
}
I found that I did not need to use NSRange. My code can do the operations beginning with a decimal number or a floating number.
-(IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [[sender titleLabel] text];
if(userIsInTheMiddleOfTypingANumber)
{
[display setText:[[display text] stringByAppendingFormat:digit]];
}
else
{
if([digit isEqual:#"."]) //check for the decimal and append to the digits
[display setText:#"."];
else
[display setText:digit];
userIsInTheMiddleOfTypingANumber = YES;
}
}
I couldn't get any of the above code to work with the CS193P Fall 2011 Calculator.
Here is how I finally got it to work.
-(IBAction)digitPressed:(UIButton *)sender
{ // Begin ACTION
NSString *digit = sender.currentTitle;
if (self.userIsInTheMiddleOfEnteringNumber)
{
//Check to see if a decimal was entered
if ([digit isEqual:#"."])
{
//Check to see if a decimal was entered before
if (self.decimalEntered)
{
[self Display];
}
else
{
self.Display.text = [self.Display.text stringByAppendingString: digit];
self.decimalEntered = YES;
}
}
else
{
self.Display.text = [self.Display.text stringByAppendingString: digit];
}
}
else
{
if ([digit isEqual:#"."])
{
//First Decimal Entered";
self.Display.text = digit;
self.decimalEntered = YES;
}
else
{
//First Number Entered";
self.Display.text = digit;
}
// This tells the Brain that the user is typing
self.userIsInTheMiddleOfEnteringNumber = YES;
}
} // End ACTION
I believe this is simpler.
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit =[[sender titleLabel] text];
NSRange range =[[display text] rangeOfString:#"."];
if (([digit isEqual:#"."])&&(range.location==NSNotFound)){midtype=YES;}
if (midtype){
if (([digit isEqual:#"."])&&(range.location!=NSNotFound))
{[display setText:[display text]];}
else {[display setText:[[display text]stringByAppendingString:digit]];}
}
else {[display setText:digit];
midtype =YES;
}
}
This is my first solution and doesn't look objective-C style but it works...
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [sender currentTitle];
if ([digit isEqualToString:#"."]) {
self.numberOfDot ++;
}
if (self.userIsInTheMiddleOfEnteringANumber){
if (self.numberOfDot < 2) {
self.display.text = [self.display.text stringByAppendingString:digit];
}
else
if (![digit isEqualToString:#"."])
self.display.text = [self.display.text stringByAppendingString:digit];
}
else {
self.display.text = digit;
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}

How to extract the data I want in NSString?

I have a NSString like this:
456673\tSomething
But I would like to extract Something only.... ...
All the data must be in this format ....
xxxx\tyyyy
How can I split it bases on \t? thank you.
You may be looking for this instance method:
- (NSArray *)componentsSeparatedByString:(NSString *)separator
If that fails your needs and you want something more powerful, I can personally recommend RegexKitLite. RegexKitLite adds the power of regular expressions to NSString in the form of a category.
I've added a category to NSString for convenience (class: NSString+Utility):
- (NSString *)substringFromFirstOccurenceOfString:(NSString *)string {
NSRange range = [self rangeOfString:string];
if (range.location != NSIntegerMax) {
int index = range.location + range.length;
return [self substringFromIndex:index];
} else {
return self;
}
}
- (NSString *)substringFromLastOccurenceOfString:(NSString *)string {
NSRange range = [self rangeOfString:string options:NSBackwardsSearch];
if (range.location != NSIntegerMax) {
int index = range.location + range.length;
return [self substringFromIndex:index];
} else {
return self;
}
}
- (NSString *)substringToFirstOccurenceOfString:(NSString *)string {
NSRange range = [self rangeOfString:string];
if (range.location != NSIntegerMax) {
int index = range.location + range.length;
return [self substringToIndex:index];
} else {
return self;
}
}
- (NSString *)substringToLastOccurenceOfString:(NSString *)string {
NSRange range = [self rangeOfString:string options:NSBackwardsSearch];
if (range.location != NSIntegerMax) {
int index = range.location;
return [self substringToIndex:index];
} else {
return self;
}
}