I store user's answers inside NSMutableString element of array. i want to show a pop up (call popGoResultsAlert) when all of the array's element has the value and user would complete the questionary , i search over the internet but didn't succeed to find the solution for that.
here is my code :
in first class
[UserData updateUserAnswerValues:[userData objectForKey:#"userAnswerValues"]];
//second class ,part of the userData.m
static NSMutableArray *userAnswerValues;
+ (NSMutableArray *)getAnswersCompleted {
return userAnswerValues;
}
+ (void)updateUserAnswerValues:(NSArray *)newAnswerValues
{
userAnswerValues = [[NSMutableArray alloc] init];
[userAnswerValues addObjectsFromArray:newAnswerValues];
}
+ (void)updateUserAnswerValueWithIndex:(NSUInteger)index andValue:(NSMutableString*)value
{
[userAnswerValues setObject:value atIndexedSubscript:index];
}
in 3rd class:
- (void)viewWillAppear:(BOOL)animated
{
NSMutableArray *userAnswerValues = [UserData getAnswersCompleted];
for (int i=0; i<userAnswerValues.count; i++) {
id object = userAnswerValues[i];// similar to [myArray objectAtIndex:0]
if(object && [object length] !=0 && i!=0)
{
[self popGoResultsAlert];
break;
} else if (!object) {
continue;
}
}
}
Edit :
//4th class , here seems the origin data is populated to the userAnswerValues base on what user pick from PickerView , that index has the value and that value is put by selectedOptionValue variable ... I have debug the userAnswerValues and notice the value has 56 elements like userAnswerValues = ( "", "", "", "", "", "", "", "", 4, 3, 4, 3, "", ... (fill the rest with ,"" until 56 items> , "" );
so whenever a user select a value in PickerView one of the above element filled out with index number , so my question is how search through these mutable array and see if all item has value...
NSUInteger index = [self.currentQuestion.index integerValue];
[UserData updateUserAnswerWithIndex:index andValue:self.selectedOptionIndex];
Option *selectedOption = [self.currentOptions objectAtIndex:[self.selectedOptionIndex integerValue]];
NSString *selectedOptionValue = selectedOption.value;
[UserData updateUserAnswerValueWithIndex:index andValue:selectedOptionValue];
there is 3 section of questionary that store all the answer's value in a single and same array. with above code , the alert pop up whenever each of 3 section would be completed , my intend is it would only show pop up when all 3 section is completed....
I have test [object length] !=0 , ![object isEqual:[NSNull null]] , ![object isEqualToString:#""] with no luck , all of the 3 has same behaviour (show pop up after each section is completed ,
These project has not written by me from the scratch so i am trying to debug and fix some of it's bugs , when i debug userAnswerValues , i see that the items of NSMutableArray had different type in different elements type, as you see item 32th is _NSFConstantString with empty value , while the item 33th is NSTagedPointerString... please see the attached file for more details.
What I think you need is very similar to the previous answer. Here, I'll translate to your data names.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
BOOL showPopup = YES; // Assume success
NSMutableArray *userAnswerValues = [UserData getAnswersCompleted];
// Try to go all the way through the array without finding an empty string
for (int i = 0; i < userAnswerValues.count; i++) {
id object = userAnswerValues[i];
if ([object length] == 0) {
showPopup = NO; // Something is not filled in
break;
}
}
if (showPopup) {
[self popGoResultsAlert];
}
}
Bool nilBool = 0;
for (int i = 0 ; i < yourArray.count; i ++)
{
NSString *value = [yourArray ObjectAtIndex:i];
if([value isEqual: #""] || value == nil)
{
nilBool = 1;
}
}
if(nilBool)
{
//one if your values is nil!
}
else
{
//all values are filled, you are good to go
}
I have a name as "Ryan" and next time entering "Ryan" it should check it has the value,So it should make it "Ryan_1". The same way it should check if anytime someone added again "Ryan" it should change it to "Ryan_2".
Example:
nameArray = ["Ryan","John","Ryan_2","Rhonda","Ryan_3","Kylie","Ryan_4","John_2"];
I am using below code which is working fine while adding the name first time.
But when I am coming back to the section and editing value Ex: I changed Ryan_2 to "xyz" and again thought of keeping "Ryan" the saved value is becoming "Ryan_4" where as it supposed to be "Ryan_2" in the array. And let say if I am changing "Ryan_4" to "somenewName" now the numbering of other duplicate names also get rearranged.
NSMutableArray *array = [[NSMutableArray alloc]init];
int occurrences = 0;
for(NSString *string in nameArray) {
if ([value isKindOfClass:[NSString class]]) {
if ([string containsString:value]) {
[array addObject:string];
}
occurrences+= ([string containsString:value] ? 1 : 0);
}
}
if ([value isKindOfClass:[NSString class]]) {
if (![value isEqualToString:#""]) {
if (occurrences > 1) {
value = [value stringByAppendingFormat:#"_%d", occurrences];
}
}
}
I would recommend an extension like this:
extension NSMutableArray {
public func appendWithSuffix(strNewEntry:String) {
var n = 1
var new = strNewEntry
if self.containsObject(strNewEntry) {
new = strNewEntry + "_\(n)"
while self.containsObject( new ){
n += 1
new = strNewEntry + "_\(n)"
}
}
self.addObject( new )
}}
It will look for an exact match and insert if none is found, i.e it will add "Ryan_5" instead of "Ryan", "John_3" instead of "John" and so on.
Another approach may be to iterate thru all entries for comparison or filter the array with "namexy".hasPrefix("Ryan") to get max index of name to be inserted.
- (IBAction)SaveText:(id)sender
{
if (array.count==0)
{
[array addObject:_txtAddText.text];
}else
{
for(NSString *string in array)
{
if ([string containsString:_txtAddText.text] )
{
count = count+1;
NSString *Localstring =[NSString stringWithFormat:#"%#%d",[string stringByAppendingString:#"_"],count];
NSLog(#"%#",Localstring);
[array addObject:Localstring];
break;
}else
{
[array addObject:_txtAddText.text];
}
}
}
NSLog(#"%#",array);
}
for (int i = 0; i< [delarsInfoArray count] ; i++)
{
NSString *lattitudeValue;
NSString *longitudeValue;
if ([[delarsInfoArray objectAtIndex:i]count]>1) {
lattitudeValue = [[[delarsInfoArray objectAtIndex:i]valueForKey:#"LATITUDE"]objectAtIndex:1];
longitudeValue = [[[delarsInfoArray objectAtIndex:i]valueForKey:#"LONGITUDE"]objectAtIndex:0];
}
else
{
lattitudeValue = #"";
longitudeValue = #"";
}
CLLocationCoordinate2D pinLocation;
if(([lattitudeValue floatValue] != 0) && ([longitudeValue floatValue] != 0) ) {
mapRegion.center.latitude = [lattitudeValue floatValue];
mapRegion.center.longitude = [longitudeValue floatValue];
if(pinLocation.latitude !=0 && pinLocation.longitude !=0) {
myAnnotation1 = [[MyAnnotation alloc] init];
if ([[delarsInfoArray objectAtIndex:i] count] == 0) {
myAnnotation1.title = #"";
myAnnotation1.subtitle = #"";
}
else
{
// NSLog(#"====== delears array is===%#",delarsInfoArray);
NSLog(#"===== delears array count is %d",[delarsInfoArray count]);
if ([[[delarsInfoArray objectAtIndex:i]valueForKey:#"Address"]objectAtIndex:2] !=nil)
{
myAnnotation1.title = [[[delarsInfoArray objectAtIndex:i]valueForKey:#"Address"]objectAtIndex:2];
}
if ([[[delarsInfoArray objectAtIndex:i]valueForKey:#"City"]objectAtIndex:3]!= nil) {
myAnnotation1.subtitle = [[[delarsInfoArray objectAtIndex:i]valueForKey:#"City"]objectAtIndex:3];
}
NSLog(#"%#",[[[delarsInfoArray objectAtIndex:i]valueForKey:#"City"]objectAtIndex:3]);
}
[dealerMapView setRegion:mapRegion animated:YES];
[dealerMapView addAnnotation:myAnnotation1];
myAnnotation1.coordinate = mapRegion.center;
[myAnnotation1 release];
}
}
}
The above code is written in the viewWillAppear.After loading the map in to the view,when i clicked on the map.app gets crashed.How can solve this crash?
There are a lot of issues here, but the one that leaps out to the top of the list are the lines that read:
if ([[[delarsInfoArray objectAtIndex:i]valueForKey:#"Address"]objectAtIndex:2] !=nil)
...
and
if ([[[delarsInfoArray objectAtIndex:i]valueForKey:#"City"]objectAtIndex:3]!= nil) {
...
The problem is that objectAtIndex of a valueForKey of an array will never be nil. You can't store a nil in an array, so what valueForKey does, if it doesn't find a value, is it uses a NSNull object, [NSNull null]. That designates that there was no value found, but uses NSNull (which can be added to the array) instead of nil (which can't).
The problem is likely that there is some subsequent code (for example, the code that tries to figure out the size of the callout bubble) which tries to get the length of the string, but since you stored a NSNull, it's trying to call the length method and it's failing.
You could fix this a number of ways, such as:
if ([[[delarsInfoArray objectAtIndex:i]valueForKey:#"Address"]objectAtIndex:2] != [NSNull null])
...
I've set up a simple if statement that says if the input length is equal to 3 make the next character a "-".
It works well, but I'd like the "-" to automatically be put there after I press my button for the 3rd time. So I press, "1", "2", then when I press the "3" it automatically puts a "-" directly afterwards. Currently the "-" only gets placed when I hit the button for the 4th time?
-(IBAction)buttonDigitPressed:(id)sender {
NSString *val = phoneNumberLabel.text;
int length = [val length];
} else {
NSString *tagValue = [NSString stringWithFormat:#"%d", [sender tag]];
phoneNumberLabel.text = [val stringByAppendingString: tagValue];
if (length == 3) {
phoneNumberLabel.text = [val stringByAppendingString:#"-"];
}
if (length == 7) {
phoneNumberLabel.text = [val stringByAppendingString:#"-"];
}
}
}
Any help would be appreciated, greatly! Thanks!
-(IBAction)buttonDigitPressed:(id)sender {
NSString *val = phoneNumberLabel.text;
NSString *newValue = #"";
NSString *dash = #"";
int length = [val length];
if ( ((length == 3) || (length == 7)) ) {
dash = #"-";
}
newValue = [NSString stringWithFormat:#"%#%#%d", val, dash, [sender tag]];
phoneNumberLabel.text = newValue;
}
Add the following code in buttonClicked method
if ([myLabel.text length] == 3)
{
myLabel.text = [val stringByAppendingString:#"-"];
}
Just add that code in the same method after you update the label with the integer.
Try this method,hope it will help you.
Keep UILabel object blank in xib.
- (IBAction)pressAction:(UIButton*)sender
{
if (lbl.text.length<=2) {
lbl.text=[lbl.text stringByAppendingFormat:#"%i",sender.tag];
}
if (lbl.text.length>=3){
lbl.text=[lbl.text stringByAppendingString:#"-"];
}
}
You can send the button the events. like [button sendActionsForControlEvents:UIControlEventTouchUpInside]
Or even perform selector after delay may do the trick for you.
both the cases you need not press a button
For the addition of "-" just check how many characters have been entered and when the third character has been entered add the "-".
How do I test if an NSString is empty in Objective-C?
You can check if [string length] == 0. This will check if it's a valid but empty string (#"") as well as if it's nil, since calling length on nil will also return 0.
Marc's answer is correct. But I'll take this opportunity to include a pointer to Wil Shipley's generalized isEmpty, which he shared on his blog:
static inline BOOL IsEmpty(id thing) {
return thing == nil
|| ([thing respondsToSelector:#selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:#selector(count)]
&& [(NSArray *)thing count] == 0);
}
The first approach is valid, but doesn't work if your string has blank spaces (#" "). So you must clear this white spaces before testing it.
This code clear all the blank spaces on both sides of the string:
[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];
One good idea is create one macro, so you don't have to type this monster line:
#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]
Now you can use:
NSString *emptyString = #" ";
if ( [allTrim( emptyString ) length] == 0 ) NSLog(#"Is empty!");
One of the best solution I ever seen (better than Matt G's one) is this improved inline function I picked up on some Git Hub repo (Wil Shipley's one, but I can't find the link) :
// Check if the "thing" passed is empty
static inline BOOL isEmpty(id thing) {
return thing == nil
|| [thing isKindOfClass:[NSNull class]]
|| ([thing respondsToSelector:#selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:#selector(count)]
&& [(NSArray *)thing count] == 0);
}
You should better use this category:
#implementation NSString (Empty)
- (BOOL) isWhitespace{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
#end
Another option is to check if it is equal to #"" with isEqualToString: like so:
if ([myString isEqualToString:#""]) {
NSLog(#"myString IS empty!");
} else {
NSLog(#"myString IS NOT empty, it is: %#", myString);
}
I put this:
#implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
return !(self == nil
|| [self isKindOfClass:[NSNull class]]
|| ([self respondsToSelector:#selector(length)]
&& [(NSData *)self length] == 0)
|| ([self respondsToSelector:#selector(count)]
&& [(NSArray *)self count] == 0));
};
#end
The problem is that if self is nil, this function is never called. It'll return false, which is desired.
Just pass your string to following method:
+(BOOL)isEmpty:(NSString *)str
{
if(str.length==0 || [str isKindOfClass:[NSNull class]] || [str isEqualToString:#""]||[str isEqualToString:NULL]||[str isEqualToString:#"(null)"]||str==nil || [str isEqualToString:#"<null>"]){
return YES;
}
return NO;
}
May be this answer is the duplicate of already given answers, but i did few modification and changes in the order of checking the conditions. Please refer the below code:
+(BOOL)isStringEmpty:(NSString *)str {
if(str == nil || [str isKindOfClass:[NSNull class]] || str.length==0) {
return YES;
}
return NO;
}
Swift Version
Even though this is an Objective C question, I needed to use NSString in Swift so I will also include an answer here.
let myNSString: NSString = ""
if myNSString.length == 0 {
print("String is empty.")
}
Or if NSString is an Optional:
var myOptionalNSString: NSString? = nil
if myOptionalNSString == nil || myOptionalNSString!.length == 0 {
print("String is empty.")
}
// or alternatively...
if let myString = myOptionalNSString {
if myString.length != 0 {
print("String is not empty.")
}
}
The normal Swift String version is
let myString: String = ""
if myString.isEmpty {
print("String is empty.")
}
See also: Check empty string in Swift?
Just use one of the if else conditions as shown below:
Method 1:
if ([yourString isEqualToString:#""]) {
// yourString is empty.
} else {
// yourString has some text on it.
}
Method 2:
if ([yourString length] == 0) {
// Empty yourString
} else {
// yourString is not empty
}
Simply Check your string length
if (!yourString.length)
{
//your code
}
a message to NIL will return nil or 0, so no need to test for nil :).
Happy coding ...
You can check either your string is empty or not my using this method:
+(BOOL) isEmptyString : (NSString *)string
{
if([string length] == 0 || [string isKindOfClass:[NSNull class]] ||
[string isEqualToString:#""]||[string isEqualToString:NULL] ||
string == nil)
{
return YES; //IF String Is An Empty String
}
return NO;
}
Best practice is to make a shared class say UtilityClass and ad this method so that you would be able to use this method by just calling it through out your application.
You have 2 methods to check whether the string is empty or not:
Let's suppose your string name is NSString *strIsEmpty.
Method 1:
if(strIsEmpty.length==0)
{
//String is empty
}
else
{
//String is not empty
}
Method 2:
if([strIsEmpty isEqualToString:#""])
{
//String is empty
}
else
{
//String is not empty
}
Choose any of the above method and get to know whether string is empty or not.
It is working as charm for me
If the NSString is s
if ([s isKindOfClass:[NSNull class]] || s == nil || [s isEqualToString:#""]) {
NSLog(#"s is empty");
} else {
NSLog(#"s containing %#", s);
}
So aside from the basic concept of checking for a string length less than 1, it is important to consider context deeply.
Languages human or computer or otherwise might have different definitions of empty strings and within those same languages, additional context may further change the meaning.
Let's say empty string means "a string which does not contain any characters significant in the current context".
This could mean visually, as in color and background color are same in an attributed string. Effectively empty.
This could mean empty of meaningful characters. All dots or all dashes or all underscores might be considered empty.
Further, empty of meaningful significant characters could mean a string that has no characters the reader understands.
They could be characters in a language or characterSet defined as meaningless to the reader. We could define it a little differently to say the string forms no known words in a given language.
We could say empty is a function of the percentage of negative space in the glyphs rendered.
Even a sequence of non printable characters with no general visual representation is not truly empty. Control characters come to mind. Especially the low ASCII range (I'm surprised nobody mentioned those as they hose lots of systems and are not whitespace as they normally have no glyphs and no visual metrics). Yet the string length is not zero.
Conclusion.
Length alone is not the only measure here.
Contextual set membership is also pretty important.
Character Set membership is a very important common additional measure.
Meaningful sequences are also a fairly common one. ( think SETI or crypto or captchas )
Additional more abstract context sets also exist.
So think carefully before assuming a string is only empty based on length or whitespace.
Very useful post, to add NSDictionary support as well one small change
static inline BOOL isEmpty(id thing) {
return thing == nil
|| [thing isKindOfClass:[NSNull class]]
|| ([thing respondsToSelector:#selector(length)]
&& ![thing respondsToSelector:#selector(count)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:#selector(count)]
&& [thing count] == 0);
}
- (BOOL)isEmpty:(NSString *)string{
if ((NSNull *) string == [NSNull null]) {
return YES;
}
if (string == nil) {
return YES;
}
if ([string length] == 0) {
return YES;
}
if ([[string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
return YES;
}
if([[string stringByStrippingWhitespace] isEqualToString:#""]){
return YES;
}
return NO;
}
The best way is to use the category.
You can check the following function. Which has all the conditions to check.
-(BOOL)isNullString:(NSString *)aStr{
if([(NSNull *)aStr isKindOfClass:[NSNull class]]){
return YES;
}
if ((NSNull *)aStr == [NSNull null]) {
return YES;
}
if ([aStr isKindOfClass:[NSNull class]]){
return YES;
}
if(![[aStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]){
return YES;
}
return NO;
}
The best way in any case is to check the length of the given string.For this if your string is myString then the code is:
int len = [myString length];
if(len == 0){
NSLog(#"String is empty");
}
else{
NSLog(#"String is : %#", myString);
}
if (string.length == 0) stringIsEmpty;
check this :
if ([yourString isEqualToString:#""])
{
NsLog(#"Blank String");
}
Or
if ([yourString length] == 0)
{
NsLog(#"Blank String");
}
Hope this will help.
You can easily check if string is empty with this:
if ([yourstring isEqualToString:#""]) {
// execute your action here if string is empty
}
I have checked an empty string using below code :
//Check if we have any search terms in the search dictionary.
if( (strMyString.text==(id) [NSNull null] || [strMyString.text length]==0
|| strMyString.text isEqual:#"")) {
[AlertView showAlert:#"Please enter a valid string"];
}
Its as simple as if([myString isEqual:#""]) or if([myString isEqualToString:#""])
//Different validations:
NSString * inputStr = #"Hey ";
//Check length
[inputStr length]
//Coming from server, check if its NSNull
[inputStr isEqual:[NSNull null]] ? nil : inputStr
//For validation in allowed character set
-(BOOL)validateString:(NSString*)inputStr
{
BOOL isValid = NO;
if(!([inputStr length]>0))
{
return isValid;
}
NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:#".-"];
[allowedSet formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
if ([inputStr rangeOfCharacterFromSet:[allowedSet invertedSet]].location == NSNotFound)
{
// contains only decimal set and '-' and '.'
}
else
{
// invalid
isValid = NO;
}
return isValid;
}
You can have an empty string in two ways:
1) #"" // Does not contain space
2) #" " // Contain Space
Technically both the strings are empty. We can write both the things just by using ONE Condition
if ([firstNameTF.text stringByReplacingOccurrencesOfString:#" " withString:#""].length==0)
{
NSLog(#"Empty String");
}
else
{
NSLog(#"String contains some value");
}
Try the following
NSString *stringToCheck = #"";
if ([stringToCheck isEqualToString:#""])
{
NSLog(#"String Empty");
}
else
{
NSLog(#"String Not Empty");
}
Based on multiple answers I have created a ready to use category combining #iDevAmit and #user238824 answers.
Specifically it goes in the following order
Check for null/nil
Check if if string is empty using it's length count.
Check if string is white spaces.
Header
//
// NSString+Empty.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
#interface NSString (Empty)
- (BOOL)isEmptyOrWhiteSpacesOrNil;
#end
NS_ASSUME_NONNULL_END
Implementation
//
// NSString+Empty.m
#import "NSString+Empty.h"
#implementation NSString (Empty)
- (BOOL) isWhitespace{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
- (BOOL)isEmptyOrWhiteSpacesOrNil {
if(self == nil || [self isKindOfClass:[NSNull class]] || self.length==0 || [self isWhitespace] == YES) {
return YES;
}
return NO;
}
#end
/*
Credits
1. https://stackoverflow.com/a/24506942/7551807
2. https://stackoverflow.com/a/1963273/7551807
*/
Usage:
of-course the function will never be triggered if your string is null. Case one is there just for extra security. I advice checking for nullability before attempting to use this method.
if (myString) {
if [myString isEmptyOrWhiteSpacesOrNil] {
// String is empty
}
} else {
// String is null
}
if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
NSLog(#"String is empty");
}
else{
NSLog(#"String is not empty");
}