Printing values of UITextField to NSLog - iphone

I have a Textfield, and when i print its text to a NSLog, i get the output as (null). I want to detect this how can i do this programatically.
I have tried several approaches and all of the following failed.
NSLog (#"Print %# ", textfield.text);
if ([textfield.text isEqualToString:#""]) {}
if ([textfield.text isEqualToString:#"(null)"]) {}
if ([textfield.text isEqualToString:nil]) {}
How can i detect (null) which is returned when printed using NSLog ?

I think you mean something like this:
if (textfield.text == nil)
{
NSLog( #"textfield is nil");
} else {
if( [textfield.text length] == 0 )
{
NSLog( #"textfield has zero length")
} else {
NSLog( #"textfield is %#", textfield.text);
}
}

You can do it using
If([textField.text isEqualToString:#""])
{
//Your code ....
}
or you can do it with
if(textField.text == Nil)
{
//Your code ....
}
third option is that
if([textField.text length] == 0)
{
//Your code ....
}

Related

iPhone Check Empty dictionary

if ([dict objectForKey:#"photo"] !=(id)[NSNull null])
{NSLOG(#"dictinary is not empty")}
This is not working for me. to check empty tag
Use count.
For example:
if ([dict count] == 0) {
NSLog("empty");
}
If you want to check for a key then:
if([dict objectForKey:#"photo"]) {
NSLog(#"There's an object in photo");
}
This is working for me. You can handle Null with this code.
[dict isKindOfClass:[NSNull class]];
If the objectForKey:#"photo" is null when not present you can just do: if ([dictionary objectForKey:#"photo"]) {NSLog(#"dictionary is not empty);}
try this code for check is null value or not
NSString *value=[dict objectForKey:#"photo"];
if (value.length != 0 )
{
NSLog("not empty!");
}
else
{
NSLog("empty!");
}
I have taken into the string like :
NSString *strPhoto=[dict objectForKey:#"photo"];
if (strPhoto ==(id)[NSNull null] || [strPhoto isEqualToString:#""] || strPhoto==nil || [strPhoto length]==0) {
}
It is working for me !!!!!!!!!!

How to make a if statement with NSNull in objective-c

I am develop a iPhone application, in which i need to use JSON to receive data from server.
In the iPhone side, I convert the data into NSMutableDictionary.
However, there is a date type data are null.
I use the following sentence to read the date.
NSString *arriveTime = [taskDic objectForKey:#"arriveTime"];
NSLog(#"%#", arriveTime);
if (arriveTime) {
job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000];
}
When the arriveTime is null, how can i make the if statement. I have tried [arriveTime length] != 0, but i doesn't work, because the arriveTime is a NSNull and doesn't have this method.
the NSNull instance is a singleton. you can use a simple pointer comparison to accomplish this:
if (arriveTime == nil) { NSLog(#"it's nil"); }
else if (arriveTime == (id)[NSNull null]) { // << the magic bit!
NSLog(#"it's NSNull");
}
else { NSLog(#"it's %#", arriveTime); }
alternatively, you could use isKindOfClass: if you find that clearer:
if (arriveTime == nil) { NSLog(#"it's nil"); }
else if ([arriveTime isKindOfClass:[NSNull class]]) {
...
In a single line
arriveTime ? job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000]; : NSLog(#"Arrive time is not yet scheduled");

objective-c none nil array comes up as nil in if/else statement

The following code is not working as expected. I am setting an array after creating a view but before displaying. I used NSLog to test that the array is set but the if/else sees the array as empty.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(#"Planlist is nil %d / has %d objects", (planListArr == nil), [planListArr count]);
if (planListArr == nil || [planListArr count] == 0) { ... }
else {
NSLog(#"Planlist is empty");
}
}
Logs
2011-09-25 13:54:39.764 myVI[2938:13303] Planlist is nil 0 / has 8 objects
2011-09-25 13:54:39.765 myVI[2938:13303] Planlist is empty
PlanList is defined as
NSArray *planListArr;
#property (nonatomic, retain) NSArray *planListArr;
if (planListArr == nil || [planListArr count] == 0) { ... }
else {
NSLog(#"Planlist is empty");
}
Expanded, this becomes:
if (planListArr == nil || [planListArr count] == 0) {
...
} else {
NSLog(#"Planlist is empty");
}
So basically, it looks like you have your NSLog() statement in the wrong branch.
(!plainListArray && [plainListArray count]>0) ? NSLog(#"PlainList array has %d items",[plainListArray count] : NSLog(#"Oops! Array is not been initialized or it has no items");

NSString is empty

How do you test if an NSString is empty? or all whitespace or nil? with a single method call?
You can try something like this:
#implementation NSString (JRAdditions)
+ (BOOL)isStringEmpty:(NSString *)string {
if([string length] == 0) { //string is empty or nil
return YES;
}
if(![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
//string is all whitespace
return YES;
}
return NO;
}
#end
Check out the NSString reference on ADC.
This is what I use, an Extension to NSString:
+ (BOOL)isEmptyString:(NSString *)string;
// Returns YES if the string is nil or equal to #""
{
// Note that [string length] == 0 can be false when [string isEqualToString:#""] is true, because these are Unicode strings.
if (((NSNull *) string == [NSNull null]) || (string == nil) ) {
return YES;
}
string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([string isEqualToString:#""]) {
return YES;
}
return NO;
}
I use,
+ (BOOL ) stringIsEmpty:(NSString *) aString {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
} else {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
+ (BOOL ) stringIsEmpty:(NSString *) aString shouldCleanWhiteSpace:(BOOL)cleanWhileSpace {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
}
if (cleanWhileSpace) {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
I hate to throw another log on this exceptionally old fire, but I'm leery about editing someone else's answer - especially when it's the selected answer.
Jacob asked a follow up question: How can I do this with a single method call?
The answer is, by creating a category - which basically extends the functionality of a base Objective-C class - and writing a "shorthand" method for all the other code.
However, technically, a string with white space characters is not empty - it just doesn't contain any visible glyphs (for the last couple of years I've been using a method called isEmptyString: and converted today after reading this question, answer, and comment set).
To create a category go to Option+Click -> New File... (or File -> New -> File... or just command+n) -> choose Objective-C Category. Pick a name for the category (this will help namespace it and reduce possible future conflicts) - choose NSString from the "Category on" drop down - save the file somewhere. (Note: The file will automatically be named NSString+YourCategoryName.h and .m.)
I personally appreciate the self-documenting nature of Objective-C; therefore, I have created the following category method on NSString modifying my original isEmptyString: method and opting for a more aptly declared method (I trust the compiler to compress the code later - maybe a little too much).
Header (.h):
#import <Foundation/Foundation.h>
#interface NSString (YourCategoryName)
/*! Strips the string of white space characters (inlcuding new line characters).
#param string NSString object to be tested - if passed nil or #"" return will
be negative
#return BOOL if modified string length is greater than 0, returns YES;
otherwise, returns NO */
+ (BOOL)visibleGlyphsExistInString:(NSString *)string;
#end
Implementation (.m):
#implementation NSString (YourCategoryName)
+ (BOOL)visibleGlyphsExistInString:(NSString *)string
{
// copying string should ensure retain count does not increase
// it was a recommendation I saw somewhere (I think on stack),
// made sense, but not sure if still necessary/recommended with ARC
NSString *copy = [string copy];
// assume the string has visible glyphs
BOOL visibleGlyphsExist = YES;
if (
copy == nil
|| copy.length == 0
|| [[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0
) {
// if the string is nil, no visible characters would exist
// if the string length is 0, no visible characters would exist
// and, of course, if the length after stripping the white space
// is 0, the string contains no visible glyphs
visibleGlyphsExist = NO;
}
return visibleGlyphsExist;
}
#end
To call the method be sure to #import the NSString+MyCategoryName.h file into the .h or .m (I prefer the .m for categories) class where you are running this sort of validation and do the following:
NSString* myString = #""; // or nil, or tabs, or spaces, or something else
BOOL hasGlyphs = [NSString visibleGlyphsExistInString:myString];
Hopefully that covers all the bases. I remember when I first started developing for Objective-C the category thing was one of those "huh?" ordeals for me - but now I use them quite a bit to increase reusability.
Edit: And I suppose, technically, if we're stripping characters, this:
[[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0
Is really all that is needed (it should do everything that category method does, including the copy), but I could be wrong on that score.
I'm using this define as it works with nil strings as well as empty strings:
#define STR_EMPTY(str) \
str.length == 0
Actually now its like this:
#define STR_EMPTY(str) \
(![str isKindOfClass:[NSString class]] || str.length == 0)
Maybe you can try something like this:
+ (BOOL)stringIsEmpty:(NSString *)str
{
return (str == nil) || (([str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]).length == 0);
}
Based on the Jacob Relkin answer and Jonathan comment:
#implementation TextUtils
+ (BOOL)isEmpty:(NSString*) string {
if([string length] == 0 || ![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
return YES;
}
return NO;
}
#end
Should be easier:
if (![[string stringByReplacingOccurencesOfString:#" " withString:#""] length]) { NSLog(#"This string is empty"); }

Validate against empty UITextField?

What is the value of a UITextField when it is empty? I can't seem to get this right.
I've tried (where `phraseBox' it the name of the said UITextField
if(phraseBox.text != #""){
and
if(phraseBox.text != nil){
What am I missing?
// Check to see if it's blank
if([phraseBox.text isEqualToString:#""]) {
// There's no text in the box.
}
// Check to see if it's NOT blank
if(![phraseBox.text isEqualToString:#""]) {
// There's text in the box.
}
found this at apple discussions when searching for the same thing,thought ill post it here too.
check the length of the string :
NSString *value = textField.text;
if([value length] == 0) {
}
or optionally trim whitespaces from it before validation,so user cannot enter spaces instead.works well for usernames.
NSString *value = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if([value length] == 0) {
// Alert the user they forgot something
}
Try following code
textField.text is a string value so we are checking it like this
if([txtPhraseBox.text isEqualToString:#""])
{
// There's no text in the box.
}
else
{
NSLog(#"Text Field Text == : %# ",txtPhraseBox.text);
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *fullText = [textField.text stringByAppendingString:string];
if ((range.location == 0) && [self isABackSpace:string]) {
//the textFiled will be empty
}
return YES;
}
-(BOOL)isABackSpace:(NSString*)string {
NSString* check =#"Check";
check = [check stringByAppendingString:string];
if ([check isEqualToString:#"Check"]) {
return YES;
}
return NO;
}
Use for text field validation:
-(BOOL)validation{
if ([emailtextfield.text length] <= 0) {
[UIAlertView showAlertViewWithTitle:AlertTitle message:AlertWhenemailblank];
return NO; }
return YES;}
Actually, I ran into slight problems using Raphael's approach with multiple text fields. Here's what I came up with:
if ((usernameTextField.text.length > 0) && (passwordTextField.text.length > 0)) {
loginButton.enabled = YES;
} else {
loginButton.enabled = NO;
}
Validation against empty UITextfield. if you don't want that UITextField should not accept blank white spaces. Use this code snippet:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound) {
return YES;
} else {
return NO;
}
}