I record the value of the text in my UITextField and I want to compare the text to the original text field value later. I try something like this, but I never get the NSLog to be displayed. Any ideas why?
defaultTopicText = topicTextField.text;
if ([topicTextField.text isEqualToString:defaultTopicText]){
NSLog(#"YES");
}else{
NSLog(topicTextField.text);
NSLog(defaultTopicText);
}
The code looks exactly like you see it. The first line I assign the value and the other - I compare with it. And it's not being called.
EDIT:
The code itself IS getting called and I also get the same values when I put them in NSLog. Might the problem be that the text field contains #"\n" characters?
NSLog gives me this:
2013-03-18 20:45:22.037 myapp[524:907]
Here comes the text
2013-03-18 20:45:22.039 myapp[524:907]
Here comes the text
Try to print out the value of the topicTextField.text and see what is shows. otherwise set the breakpoints to see if you are reaching to that particular line of code.
You coud also try comparing after removing the white spaces and new line, if there might be any
NSString *trimmmedText = [topicTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([trimmmedText isEqualToString:defaultTopicText]){
NSLog(#"YES");
}
Try changing to this:
NSString *newString = [defaultTopicText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([newString isEqualToString:defaultTopicText]){
NSLog(#"YES");
}
I typed the following the figured out the answer...
running this should give you your answer:
if(!defaultTopicText){
NSLog(#"defaultTopicText is nil");
}else{
NSLog(#"defaultTopicText is a: %#".[defaultTopicText classname]);
}
defaultTopicText = topicTextField.text;
if ([topicTextField.text localizedCaseInsensitiveCompare:defaultTopicText] == NSOrderedSame){
NSLog(#"YES");
}else{
NSLog(#"\"%#\" != \"%#\"",defaultTopicText, topicTextField.text);
}
Then I realized: topicTextField.text can only not be the same object as itself using this comparison method if it is nil.
topicTextField.text has to be nil... so it ends up executing:
id var = nil;
[var isEqual:nil];
and the runtime makes that return 0;
... so fix your outlet to topicTextField
Related
I am using an app to lock, unlock, and open the trunk of my car. The only problem is that I can't figure out how to modify the Xcode project so there are 3 buttons. Basically right now if I type "U" then enter- the car unlocks, "L" then enter- the car locks, and "T" then enter- the trunk opens. I want to add three buttons that simulate these three things and eliminate the typing all together. If you want to see my adruino or xcode project code I can upload those. I have put some code about the text box below.
BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSString *text = textField.text;
NSNumber *form = [NSNumber numberWithBool:NO];
NSString *s;
NSData *d;
if (text.length > 16)
s = [text substringToIndex:16];
else
s = text;
d = [s dataUsingEncoding:NSUTF8StringEncoding];
if (bleShield.activePeripheral.state == CBPeripheralStateConnected) {
[bleShield write:d];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:text, TEXT_STR, form, FORM, nil];
[tableData addObject:dict];
[_tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
NSLog(#"%f", _tableView.contentOffset.y);
[self.tableView reloadData];
}
textField.text = #"";
return YES;
Thanks for the help!
Your view controller probably has a textFieldShouldReturn method which is taking the string value from the text field and building a parameter to a call that initiates sending the command. If not this method then perhaps its action method linked to the text field.
You'll need to duplicate parts of that code into a method that receives a string parameter instead of taking it from the text field, say named sendLockCommand:(NSString *)commandString (assuming you're coding in Objective-C, also like that repo).
Make action methods for your buttons, something like lockDoors, unlockDoors, openTrunk, in each call [self sendLockCommand:#"L"], each with the appropriate string. Wire up the buttons to those actions and you're good to go.
I want to set the title of my navigation bar with a json title.
I tried:
[self setTitle:[self.defineJsonDataforSurveyQuestion objectForKey:#"SurveyName"]];
[self.navigationController setTitle:[self.defineJsonDataforSurveyQuestion objectForKey:#"SurveyName"]];
It works if manually set the title but I get nothing with the json. I know I am getting the correct value and and parsing the json right because it shows correct in the NSLog.
I have no errors and the title just comes up blank.
2013-05-25 13:37:26.863 [1657:907] Survey name for title:Filter Inspection
Please help.
objectForKey: returns an object, which could be an NSString, but it doesn't have to be. When you print it with NSLog, NSLog calls 'describe' on the object, that way you still get something sensible in your log, but setTitle: doesn't do that of course, it expects an NSString object.
id title = [self.defineJsonDataforSurveyQuestion objectForKey:#"SurveyName"];
if ([[title class] isKindOfClass:[NSString class]]) {
[self.navigationController.navigationBar.topItem setTitle:title];
} else {
NSLog(#"title is not a string, but %#!", [title class]);
}
i have a uitextfield, when it is initialized and i didn't input any values into it, i found the value of the uitextfield is not null nor nil.
NSString *notes = (notesField.text)?(notesField.text):#"hello";
NSLog(#"notes: %#",notes);
it returns nothing for notes
NSString *notes1;
//or use legnth
if ([notesField.text isEqual:#""]) {
notes1=#"hello";
NSLog(#"empty textfield: %#",notes1);
//then it returns "hello"
}
else
{
notes1=notesField.text;
NSLog(#"not empty textfield: %#",notes1);
}
Why is that? Can I still user ternary operator ?
like this ?
NSString *notes = ([notesField.text length])?(notesField.text):#"hello";
You can use
NSString *notes = ([notesField.text length])?(notesField.text):#"hello";
OR
NSString *notes = ([notesField.text length]==0)?#"hello":(notesField.text);
OR
NSString *notes = ([notesField.text isEqualToString:#""])?#"hello":(notesField.text);
And for the case when your UITextField has no entry (initial case), use the second or third option , that will be beter. NSString *notes = ([notesField.text length])?#"hello":(notesField.text); won't work fine as you expect because notesField.text will be TRUE even if there is no text in textfield. So you should use notesField.text.length or [notesField.text isEqualToString:#""].
Hope its clear now.
The docs for UITextField state
text
The text displayed by the text field.
#property(nonatomic, copy) NSString *text
Discussion
This string is #"" by default.
Note: if compiling under Xcode 5.02 or 5.1 and running in iOS earlier than iOS7, UITextField.text is initialised to nil. If running in iOS7+ it is initialised to #"".
If compiling in Xcode 4.6.3 or earlier then UITextField.text has (always) been initialised to #"", as per the documentation.
Radar bug: 16336863
UITextField must be initializing itself with a non-nil empty string. In situations where you don't care if the string is empty or nil, you can simply check the length property:
if (!notesField.text.length) {
// text is nil or empty
}
Or using the ternary operator:
NSString *s = notesField.text.length ? notesField.text : #"Default";
This works because sending the -length selector to a nil object will return a default value of 0.
That approach will work just fine.
As for why it's an empty string instead of nil, it's generally bad practice to return nil for something unless you want to indicate an error or an uninitialized state. An empty text field has a value. It's just an empty string.
I'm trying to determine the user language in iOS. StackOverflow has several answers on this topic which has greatly helped me out, such as this one: Getting current device language in iOS?
I can successfully retrieve the value I'm looking for in NSLog (i.e. "en" or "de") but every time I question this with an if/then statement it doesn't appear to work. I have this in my viewDidLoad for testing:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *myLanguage = [[NSLocale preferredLanguages] objectAtIndex:0];
NSLog(#"The current languague is %#.", myLanguage);
if (myLanguage == #"de") {
self.myLabel.text = #"German";
} else if (myLanguage == #"en") {
self.myLabel.text = #"English";
} else {
self.myLabel.text = #"didn't work";
}
}
No matter if the device is set to English or German only the last else statement is displayed. NSLog however correctly displays either en or de.
What am I doing wrong?
NSString comparison is done with isEqualToString: method. In your code you are comparing two different NSString objects, while instead you have to compare the contents of each one of them.
If you have two objects of any kind, they are always different, even if all their members have the same values. That's why methods like this exist, to compare objects based on their members.
Replace:
if (myLanguage == #"de")
with
if ([myLanguage isEqualToString:#"de"])
and the same for the else ifs in your code.
I encounter a strange problem when attempting to return a composite string in the tableView's titleForHeaderIn section.
If I NSLog the string, it seems to be good, but when i return it, it crashes !
Here's my code :
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString *title = NSLocalizedString(#"favorites",#"");
NSLog(#"%#", title); // this prints the correct title ("Items" for example...)
int number = (*_tabsections_especes)[0][0];
NSLog(#"%d", number); // this prints the correct number ( "5", for example...)
NSLog(#"%#", [NSString stringWithFormat:#"%# : %d", title, number ] );
// this prints the correct concatenated string ("Items : 5", for example);
return [NSString stringWithFormat:#"%# : %d)", title, number ];
// --> this either crashes the app, or returns anything in the title,
// for example the title of a resource image or another pointer...
}
If I replace "(*_tabsections_especes)[0][0]" by "5", for example, the problem persists.
So, it seems that the issue is about using NSLocalizedString in the stringWithFormat method, then returning it.
What am I doing wrong ?
Use this before
NSString *result = [NSString stringWithFormat:#"%# : %d)", title, number ];
return result;
or use this
NSString *result = [[NSString alloc]initStringWithFormat:#"%# : %d)", title, number ]]autorelease];
return result;
I tested your method and it works. Look for your bug elsewhere.
I have found where the problem was.
Actually it was not in tableView:titleForHeaderInSection, but rather in tableView:viewForHeaderInSection.
In fact, it is because I use a subclass of UIView for the viewForHeaderInSection.
In this subclass, I have an ivar named "title".
In the init method of this subclass, I set this ivar like this :
title = myTitle; // (myTitle is an argument of the custom init method)
And, just later, I use this title like this in the drawRect method :
[title drawAtPoint:CGPointMake(8, 9) withFont:[UIFont systemFontOfSize:19]];
This works fine if I pass a static string like #"example string" from titleForHeaderInSection, and via viewForHEaderInSection.
But not at all if I pass an autorelease object like stringWithFormat.
So, the solution is simply to retain my ivar in the subclass like this:
title = [myTitle retain];
and to release it in the dealloc method of my subclass:
[title dealloc];
Like this, it works and it doesn't crash. I hope this helps and that the explanations are clear.