Add a character to a blank textfield - iphone

I'm new to xcode and am stuck on this one action.
I'm trying to add a "Negative" sign or "-" to a field when a button is clicked.
The following code works when someone enters a number into the field... it will add or remove a negative sign to it.
However, if the field is blank and you click on the button it throws an error.
Here's the code:
- (IBAction)fPosNeg:(id)sender {
NSMutableString *str = [userFahrenheit.text mutableCopy];
char iChar = [str characterAtIndex:0];
if (iChar == '-') {
userFahrenheit.text = [userFahrenheit.text substringFromIndex:1];
} else if (iChar != '-') {
[str insertString:#"-" atIndex:0];
userFahrenheit.text = str;
} else {
userFahrenheit.text = [NSString stringWithFormat:#"-"];
}
}
Here's the error:
Terminating app due to uncaught exception 'NSRangeException', reason:
'-[__NSCFString characterAtIndex:]: Range or index out of bounds'

You need to put a check before calling this -> [str characterAtIndex:0];
check will be
if(![str isEqualToString:#""]) // so that if string is blank, you cant access its character at index 0

NSMutableString *str = [NSMutableString stringWithString:#"-Test"];
char test = [str characterAtIndex:0];
NSMutableString *strFinal;
if (test == '-') {
strFinal = [NSMutableString stringWithString:[str substringFromIndex:1]];
}
else if (test != '-') {
[str insertString:#"-" atIndex:0];
strFinal=str;
}
else {
strFinal=[NSString stringWithFormat:#"-"];
}
NSLog(#"%#",strFinal);
You can also use this.
I think it's solve your problem.

Related

NSString Variable Value disappearing after reassignment

Something strange is going on. When I reassign an NSString to my subString variable near the bottom of my code. It seems that the value of subString is empty in the output. I don't know if objectAtIndex is returning something weird or it's a memory problem. If I create a new variable instead of reassigning the value of subString, I can print see the correct value in the output console. If anyone could help me figure this out. It'd be greatly appreciated.
NSString *subString = #"";
if ([text length] > 0)
{
UITextRange *selectedRange = [_textView selectedTextRange];
UITextPosition *cursorPosition = [_textView positionFromPosition:selectedRange.start offset:0];
UITextRange *subTextRange = [_textView textRangeFromPosition:_textView.beginningOfDocument toPosition:cursorPosition];
subString = [textView textInRange:subTextRange];
}
NSLog(subString);
NSLog(#" %s", [subString hasSuffix:#" "] ? "TRUE" : "FALSE");
BOOL hasSpaceSuffix = [subString hasSuffix:#" "];
NSLog(#" %s", _taggingInProgress ? "TRUE" : "FALSE");
NSArray *substringArray = [[subString componentsSeparatedByString:#" "] retain];
if ([substringArray count] > 1) {
int index = [substringArray count];
if ([[substringArray objectAtIndex:index-1] isEqualToString:#" "])
{
NSLog(#"1st");
subString = [substringArray objectAtIndex:index-2];
NSLog(subString);
}
else
{
NSLog(#"2nd");
subString = [substringArray objectAtIndex:index-1];
NSLog(subString);
}
NSLog(#"AFTER");
NSLog(subString);
}
I think you need to use:
subString = [NSString stringWithString:[substringArray objectAtIndex:index]];
...fixed...

Performing phone number validation on textfield depending on regular expression in iPhone

I have a textfield in my application where i am performing validation for phonenumber (+00-0000000000) that user must enter first '+'then the country code which will be more than 2 digits and after the country code '-' and after '-' mobile number will be entered which be any no digits long.
I have done the code using regular expression but when I initially enter any alphabet in the textfield in place of '+' my app crashes and when I enter +00- i.e +countrycode- and then any alphabet say 'abc' it accepts which is wrong. I want that only digits and + and - must be entered in the textfield. If anything other than digits and + and - is entered for eg if an alphabet is entered in the textfield then an alertview should be shown that "Please Enter Valid Mobile Number".
This is my code:
- (BOOL)validateInputWithString:(NSString *)aString
{
NSString * const regularExpression = #"^([+]{1})([0-9]{2,6})([-]{1})([0-9]{10})$";
NSError *error = NULL;
}
-(IBAction)Check:(id)sender{
BOOL check = [self validateInputWithString:TextField.text];
if(check == YES){
NSLog(#"Hii");
NSString *string= [NSString stringWithFormat:#"%#", TextField.text];
NSArray *first = [string componentsSeparatedByString:#"-"];
NSString *second = [first objectAtIndex:1];
NSString *third = [first objectAtIndex:0];
if([second length] < 11){
NSLog(#"bang");
}
else{
NSLog(#"Fault");
}
if([third length] > 3 || [third length] < 7){
NSLog(#"Bang");
}
else{
NSLog(#"fault");
}
}
else{
NSLog(#"FAULT");
}
}
But here in my code when I enter alphabets after +countrycode- then it accepts which is wrong and when I enter alphabet initially in my textfile then my app crashes on my button click.
your app crashes because of this:
NSString *string= [NSString stringWithFormat:#"%#", TextField.text];
NSArray *first = [string componentsSeparatedByString:#"-"];
NSString *second = [first objectAtIndex:1];
NSString *third = [first objectAtIndex:0];
First of all your variable names are not good. Why is first an array, second the second string and third the first string? Makes no sense, and nobody will ever understand this code.
But your crash comes because you separate the string and then without checking if it exists you access the objectAtIndex 1. Which of course does not exist if the string does not contain -.
Something like this will fix your problem:
NSString *string= [NSString stringWithFormat:#"%#", TextField.text];
NSArray *components = [string componentsSeparatedByString:#"-"];
NSString *strBeforeDash = [components objectAtIndex:0];
if ([components count] > 2) {
NSLog(#"More than one \"-\" found");
return;
}
if ([components count == 1) {
NSLog(#"No \"-\" found");
return;
}
NSString *strAfterDash = [components objectAtIndex:1];
and - (BOOL)validateInputWithString:(NSString *)aString does not validate anything because it has neither validation code nor a return value.

Objective-c Substring Range Exception

I am creating an imap client. I want to parse body and header of incoming data but it crashes. I couldn't understand why it crashes and gives substring out of range error. How can I fix it?
I only want to check if the incoming string contains "FETCH" so I parse data, since string comes like
* FETCH or * 1 FETCH I thought checking isEqualToString range of (4,6) would be enough but that didn't work.
- (NSString*) readLine
{
NSMutableData* data = [[NSMutableData alloc] init];
unsigned char c;
for (;;) {
recv(socket_, &c, sizeof(c), 0);
if (c == '\n') {
NSString* s = [[NSString alloc] initWithData: data
encoding: NSUTF8StringEncoding];
NSString *str = [s substringWithRange:NSMakeRange(4, 6)];
if( [str isEqualToString:#"FETCH "]){
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:s];
[scanner scanUpToString:#"}" intoString:nil];
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:#"}" intoString:nil];
if([scanner scanUpToString:#"*" intoString:&substring]) {
// If the space immediately followed the }, this will be skipped
[substrings addObject:substring];
}
[scanner scanUpToString:#"}" intoString:nil]; // Scan all characters before next }
}
NSString *email;
[emailList addObject:#"Select an Email"];
for(int i=0; i<substrings.count;i++){
email = [substrings objectAtIndex:i];
[emailList addObject:email]; // add emails in emailList
}
[substrings release];
}
if (nil != s) {
NSLog(#"%#",s);
}
[data release];
return [s autorelease];
}
else {
[data appendBytes: &c length: 1];
}
}
return nil;
}
output is:
* 1 FETCH (BODY[HEADER.FIELDS (FROM SUBJECT DATE)] {149}
2011-11-07 23:32:24.363 SwitchDeneme[327:bc03] Date: Mon, 07 Nov 2011 17:00:25 -0500 (EST)
2011-11-07 23:32:24.364 SwitchDeneme[327:bc03] From: "AOLWelcomeInfo" <AOLWelcomeInfo#message.aol.com>
2011-11-07 23:32:24.365 SwitchDeneme[327:bc03] Subject: Welcome to Your New Email Account!
2011-11-07 23:32:24.367 SwitchDeneme[327:bc03] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFString substringWithRange:]: Range or index out of bounds'
terminate called throwing an exceptionsharedlibrary apply-load-rules all
The problem is that your string is likely shorter than 7 characters, meaning it does not have an index of 6.
Try something more like this:
NSRange range = [someString rangeOfString:#"FETCH "];
if( range.location != NSNotFound ) {
//found it... so now do you processing...
}
You allocate and initialize an NSData object, then use that empty data object to initialize a string, so that string is empty.

How to delete single characters in an UITextView

I have an UITextView which is for instance 380 characters in length:
NSLog(#"aTextView.text lenght %i", aTextView.text.length);
I now want to go through this text (backwards, char by char) and delete all characters which come before the last space (e.g. if the last words were "...this is an example", it want to reduce the string to "...this is an ":
for (int i = aTextView.text.length-1; i > 0; i--) {
NSString *checkedChar = [NSString stringWithFormat:#"%c", [aTextView.text characterAtIndex:i]];
NSLog(#"I currently check: %#", checkedChar);
if ([checkedChar isEqualToString:#" "]) {
// job done
i = 0; // this ends the loop
} else {
I need something like [aTextView.text removeCharacterAtIndex:i];
}
}
How do I achieve this? I couldn't find any methods in the docs and would be very grateful for suggestions.
EDIT:
NSString *myString = aTextView.text;
NSRange range = [myString rangeOfString:#" " options:NSBackwardsSearch];
NSString *oldText = [myString subStringToIndex:range.location];
NSString *newText = [myString subStringFromIndex:range.location];
NSLog(#"++++ OLD TEXT ++++: %#", oldText);
NSLog(#"++++ NEW TEXT ++++: %#", newText);
aTextView.text = oldText;
This crashes my app... I am calling this from - (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString *)aText
I get the error message: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString subStringToIndex:]: unrecognized selector sent to instance 0x4e33850'
And xCode gives me the warning the subStringToIndex may not respond...
You don't need a loop to do this - take a look at NSString' rangeOfString:options: and substringToIndex: methods. For example :
NSRange range = [myString rangeOfString:#" " options:NSBackwardsSearch];
NSString *newString = [myString substringToIndex:range.location];
Hope that helps.
NB Don't forget to check that your string definitely contains a space ;)
This is very easy in iOS 5 or later:
// This is your delete button method.
-(IBAction)btnDelete:(id)sender
{
// txtView is UITextView
if([txtView.text length] > 0)
{
[txtView deleteBackward];
}
}

how to validate textfield that allows . only once with in the textfield

I have 4 text fields in my application.
I validate my textfields as textfield allow 0,1,...9 and .,for that i write code as fallows
- (IBAction) textfield:(id)sender {
if ([textfield.text length] > 0) {
if ([textfield.text length] > 10){
textfield.text = [textfield.text substringWithRange:NSMakeRange(0, 10)];
}
else {
//retrieve last character input from texfield
int I01 = [homevalue.text length];
int Char01 = [homevalue.text characterAtIndex:I01-1];
//check and accept input if last character is a number from 0 to 9
if ( (Char01 < 46) || (Char01 > 57) || (Char01 == 47) ) {
if (I01 == 1) {
textfield.text = nil;
}
else {
textfield.text = [homevalue.text substringWithRange:NSMakeRange(0, I01-1)];
}
}
}
}
}
It works fine, Now i need to validate that . allows only once with in the textfield.
eg: 123.45
According to my code if i place again . it is allowed.
eg:123.45.678
But it wont allowed once i place . ,that textfield wont allowed.
ed:123.45678.
How can i done this,
can any one pls help me.
Thank u in advance.
Try this predicate for texts that start with a number like "23.67"
NSString *decimalRegex = #"[0-9]+([.]([0-9]+)?)?"; // #"[0-9]+[.][0-9]+";
NSPredicate *decimalTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", decimalRegex];
BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];
If you want to allow "." at the fist place like ".95" use the following regex,
NSString *decimalRegex = #"[0-9]*([.]([0-9]+)?)?"; //#"[0-9]*[.][0-9]+";
Your code should look like this,
- (IBAction)textfield:(id)sender {
int textLength = [[textfield text] length];
if (textLength > 0) {
NSString *decimalRegex = #"[0-9]+([.]([0-9]+)?)?"; //#"[0-9]+[.][0-9]+";
NSPredicate *decimalTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", decimalRegex];
BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];
if (!isValidDecimal) {
NSString *text = [[textField text] substringToIndex:textLength - 1];
[textfield setText:text]
}
}
}
I guess this should work! Give it a try!
Well you can use this method
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask range:(NSRange)aRange
on textfield.text as its a NSString only