UITextField text value returns garbage - iphone

I am trying to get a string value out of a textField when the user dismisses the keyboard. However, it seems that whenever I try to get the value, I get garbage (attempting to print out textField.text gives out garbage). What could I be doing wrong?
(The control displays fine, and I can put text values into it even).
Here's my code:
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
NSInteger currenttag = textField.tag;
NSLog(#"%d",textField.tag);
if (currenttag == 0) {
NSLog(#"%x %s",(unsigned int)textField.text,textField.text);
username = textField.text;
} else if (currenttag == 1) {
password = textField.text;
}
[textField resignFirstResponder];
return YES;
}
The fields username and passwords are nil NSString*'s, but since I will merely hold on to the NSStrings held by textField.text, it should be fine.

NSLog(#"text field text:%#",textField.text);

Have you tried using breakpoints? Have you tried NSLog(#"%#", textField.text); ?
Have you tried rewriting the function so it only displays the text?
Is the textField a valid object?

Inserting [textField retain]; as the 1st line will probably fix the problem. Just remember to add a [textField release]; at the end of the method.

Related

Make second UITextField firstresponder after the first UITextField did finish editing and press Done

I have created two UITextFields dynamically, when tapped on a certain CA Layer. I have made the first textfield the first responder, what I want is, when I enter text in first Textfield and press done, I want the second textfield to be the first responder.
n thats what I did for this in textFieldShouldReturn.
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (titleField.returnKeyType== UIReturnKeyDone) {
NSString *title = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (title.length>0 )
{
[self changeLayersTitle:title];
}
[dateField becomeFirstResponder];
if (dateField.returnKeyType==UIReturnKeyDone)
{
NSString *date = [dateField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (date.length>0)
{
[self changeLayersDate:date];
}
}
[dateField resignFirstResponder];
[bgLayer removeFromSuperlayer];
[titleField removeFromSuperview];
[dateField removeFromSuperview];
}
return NO;
}
Now, when I enter press Done after entring text in first one, it dismissed both of the textfields, bt shows me the keyboard.
So, what am I missing or did wrong or do I have to put it somewhere else. please help me out.
I'm not sure why you were comparing the returnKeyType property of the text fields. You should compare the text fields for equality, and if the return key was pressed on the first text field, then make the second text field the new responder.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == titleField) {
[dateField becomeFirstResponder];
}
else if (textField == dateField) {
// Return button pressed on 2nd field. Do something
}
return YES;
}
In your done button callback method, can't you just set your second text field as the first responder?
You don't need to resignFirstResponder on your first text field.

UITextFeld Comparison Failing

I have a UITextField and I create it like so:
firstnameField1 = [[UITextField alloc] initWithFrame:CGRectMake(85+320*4, 80, 150, 30)];
[firstnameField1 setBorderStyle:UITextBorderStyleRoundedRect];
[firstnameField1 setPlaceholder:#"Firstname"];
[firstnameField1 setDelegate:self];
[firstnameField1 setReturnKeyType:UIReturnKeyNext];
[scrollViewController addSubview:firstnameField1];
When the user taps the return key I want to check if the text field has anything typed into it, if its empty, the user hasn't typed anything, I want to return and show a label telling the user that field is required to be filled before they can continue, just like you see all over the place.
I do the following to check:
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
//Check if the user has typed anything
if (textField.text == #"") {
//If not, show 'required' labels
[firstNameRequiredLbl1 setAlpha:1];
[surnameRequiredLbl1 setAlpha:1];
[firstNameRequiredLbl2 setAlpha:1];
[surnameRequiredLbl2 setAlpha:1];
return YES;
}
//Do all my other stuff, cut out for ease of reading, 100% doesn't affect this anyway
return YES;
}
I have set a breakpoint on that last method and it jumps right past that if statement whether I type into that textfield or not.
Any ideas? Thanks.
You'll want to change textField.text == #""
to: textField.text.length == 0 or textField.text isEqualToString:#""
What the == operator is actually doing in this case is checking if the strings are stored in the same area of memory rather than whether or not they contain the same characters.
You can't compare NSString text strings that way. Use this instead:
if ([textField.text isEqualToString: #""])

Detect string or integer in Core Data

I have built in some Core Data support into my app from the Core Data Books example. The example uses Dates and Strings. However I have tried adding the ability to add and edit an Integer value.
//If the value is a string
if ([[editedObject valueForKey:editedFieldKey] isKindOfClass:[NSString class]]) {
textField.hidden = NO;
datePicker.hidden = YES;
textField.text = [editedObject valueForKey:editedFieldKey];
textField.placeholder = self.title;
[textField becomeFirstResponder];
}
//If the value is a number
else {
textField.hidden = NO;
datePicker.hidden = YES;
textField.text = [[editedObject valueForKey:editedFieldKey] stringValue];
textField.placeholder = self.title;
[textField becomeFirstResponder];
}
The first if statement is the in example code (without the check if its a string, I added that) and I added the else statement to run when its not a string but an integer. It works, however now when I edit a string it skips the if statement, so the line: if ([[editedObject valueForKey:editedFieldKey] isKindOfClass:[NSString class]]) isn't working somehow.
If you do look at the CoreDataBooks example from Apple, my code is the same, only I added a field which takes an Integer 16.
Edit
When putting a breakpoint on the first if statement and returning po [editedObject valueForKey:EditedFiledKey] in the console I get: Can't print the description of a NIL object.
I assume this is because it's before the object is made? This happens when the view appears (the view to enter a new string).
It's upon pressing the save button that this code is run:
- (IBAction)save {
// Set the action name for the undo operation.
NSUndoManager * undoManager = [[editedObject managedObjectContext] undoManager];
[undoManager setActionName:[NSString stringWithFormat:#"%#", editedFieldName]];
// Pass current value to the edited object, then pop.
if ([[editedObject valueForKey:editedFieldKey] isKindOfClass:[NSString class]]) {
[editedObject setValue:textField.text forKey:editedFieldKey];
}
else {
[editedObject setValue:[NSNumber numberWithInteger:[[textField text] integerValue]] forKey:editedFieldKey];
}
[self.navigationController popViewControllerAnimated:YES];
}
When this runs, its skips the first if statement and runes the else statement, then crashing and showing the error: Unacceptable type of value for attribute: property = "firstName"; desired type = NSString; given type = __NSCFNumber; value = 0.
firstName is the string attribute in my data model. Im guessing because that first if statement fails, its goes forward an expects an integer? Im really unsure.
OK, so based on the value being nil in the debugger, let me explain what's happening. In Objective-C, any message sent to nil object will simply do nothing, and then return nil (which happens to have exactly the same memory value as 0 and false and NO).
So you're doing this:
if ([[editedObject valueForKey:editedFieldKey] isKindOfClass:[NSString class]]) {
If editedObject is nil, then valueForKey will do nothing and return nil. Then you're sending isKindOfClass to nil which will also do nothing and return nil. Inside an if statement, nil will evaluate to NO, sending you to the else statement.
Where you do this:
textField.text = [[editedObject valueForKey:editedFieldKey] stringValue];
editedObject is nil, cascading to stringValue returning nil, and therefore you are trying to set the text field's value to nil, which is invalid and will crash your app.
The solution is to restructure your code to check for nil. Here's how I would write your code:
// don't do anything for a nil value note this will detect editedObject being nil, or the result of valueForKey: being nil.
if (![editedObject valueForKey:editedFieldKey]) {
return;
}
// figure out the string value
NSString *textFieldValue = [editedObject valueForKey:editedFieldKey];
if ([textFieldValue isKindOfClass:[NSNumber class]]) {
textFieldValue = [(NSNumber *)textFieldValue stringValue]
}
// update the text field
textField.hidden = NO;
datePicker.hidden = YES;
textField.text = textFieldValue;
textField.placeholder = self.title;
[textField becomeFirstResponder];
I tackled the same problem with more Core Data app. I also adapted the Core Data Books app. If you notice, in the original app, they use a BOOL variable (editingDate) to decide whether to show the date picker or not. I created a second BOOL variable, ('editingTextView`) and just change those BOOL variables depending on what needs to be edited. It may not be the most efficient way, but it is easy to program, and easy to follow what is already there in Core Data Books.

How to test a UITextField for being nil?

I am trying to make a part of my app where if the person doesn't change the blank text in my UITextField, then he/she can't go on to the next step. Basically, I want to test the UITextField for nil text. I have used the if (text == #"") method, but if the person clicks on the UITextField but doesn't type, then the if statement doesn't work. For some reason it doesn't think the text == nil or "". Am I implementing the code wrong. Any other options. Please help!!!
You should be checking the length of the text property:
if([[textField text] length] == 0) {
//do something...
}
Here's the category I use...
#implementation NSString (NSString+Extensions)
- (BOOL)isNotBlank {
return [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0;
}
#end
This way a nil string would evaluate to false, which is correct. Creating an isBlank would return false for nil, which isn't correct.
I have write code to check the string is empty or not. This code also check for the string only space that is also empty for store name and address etc. this will help you.
NSString *stringTemp = textField.text;
stringTemp = [stringTemp stringByReplacingOccurrencesOfString:#" " withString:#""];
if ([stringTemp isEqualToString:#""]) {
NSLog(#"Empty string");
}
else{
NSLog(#"string has some content ");
}
Thanks
If I were you I would disable and enable the button while the user is typing. Imho it's better that the button looks disabled when there is no text than having the user click the button to tell him that he is not allowed to move to the next view. Most of apples own apps do it like this.
You achieve this behavior by using the UITextFieldDelegate method like this
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// "Length of existing text" - "Length of replaced text" + "Length of replacement text"
NSInteger textLength = [aTextView.text length] - range.length + [text length];
if (textLength > 0) {
doneButton.enabled = YES;
}
else {
doneButton.enabled = NO;
}
return YES;
}
If you provide a prefilled textfield you have to enable the button in viewDidLoad (or where ever you want) and if you provide an empty field you have to disable it initally.

UITextfield clear button

How can I clear the field which currently has the cursor placed inside it?
I have tried:
if(textfield.isEditing)
textfield.text = #"";
This works for me, but if I select all 3 fields, and press the 'clear field button' all the fields clear Also instead of isEditing, I have tried to use tags on the UITextfields and do :
if(textfield.tag == 1)
textfield.text = #"";
but this has the same effect.
How can I solve this problem?
try one or both of these...
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.clearsOnBeginEditing = YES;
Then add delegate...
- (BOOL)textFieldShouldClear:(UITextField *)textField {
return YES;
}
Try out this in TextField's Delegate method didBeginEditing:
if ([textfield isFirstResponder]) {
textfield.text = #"";
}
Hope this helps you.