How to check if array is null or empty? - iphone

I want to check if my array is empty or null, and on base of which I want to create a condition for example.
if(array == EMPTY){
//do something
}
I hope I'm clear what I am asking, just need to check if my array is empty?
regards

if (!array || !array.count){
...
}
That checks if array is not nil, and if not - check if it is not empty.

if ([array count] == 0)
If the array is nil, it will be 0 as well, as nil maps to 0; therefore checking whether the array exists is unnecessary.
Also, you shouldn't use array.count as some suggested. It may -work-, but it's not a property, and will drive anyone who reads your code nuts if they know the difference between a property and a method.
UPDATE: Yes, I'm aware that years later, count is now officially a property.

you can try like this
if ([array count] == 0)

Just to be really verbose :)
if (array == nil || array.count == 0)

Best performance.
if (array.firstObject == nil)
{
// The array is empty
}
The way to go with big arrays.

if (array == (id)[NSNull null] || [array count] == 0) {
NSLog(#"array is empty");
}

Swift 3
As in latest version of swift 3 the ability to compare optionals with > and < is not avaliable
It is still possible to compare optionals with ==, so the best way to check if an optional array contains values is:
if array?.isEmpty == false {
print("There are objects!")
}
as per array count
if array?.count ?? 0 > 0 {
print("There are objects!")
}
There are other ways also and can be checked here
link to the answer

As nil maps to 0, which equals NO, the most elegant way should be
if (![array count])
the '==' operator is not necessary.

You can also do this kind of test using
if (nrow>0).
If your data object is not formally an array, it may work better.

null and empty are not the same things , i suggest you treat them in differently
if (array == [NSNull null]) {
NSLog(#"It's null");
} else if (array == nil || [array count] == 0) {
NSLog(#"It's empty");
}

if (array == nil || array.count == 0 || [array isEqaul [NSNull Null]])

In Swift 4
if (array.isEmpty) {
print("Array is empty")
}
else{
print("Array is not empty")
}

Related

How can I write down a shortened if condition? [duplicate]

This question already has answers here:
How to check if an element is in an array
(18 answers)
How to compare one value against multiple values - Swift
(8 answers)
How to find index of list item in Swift?
(23 answers)
Closed 4 years ago.
Does anyone have an idea how to write the following code in a shortened form?
if self.atPoint(locationUser) == blueMarkArray[0] || self.atPoint(locationUser) == blueMarkArray[1] || self.atPoint(locationUser) == blueMarkArray[2] || self.atPoint(locationUser) == blueMarkArray[3] || self.atPoint(locationUser) == blueMarkArray[4] || self.atPoint(locationUser) == blueMarkArray[5] || self.atPoint(locationUser) == blueMarkArray[6]{
print("its here")
}
Furthermore, I don't want to commit myself to a fixed number of elements in the blueMarkArray array. It should be as variable as possible, because for example it can contain 4 elements, but also 12 elements.
For each answer I am very grateful.
EDIT:
How can you access the found element if I want to write the following: someNode.position = elementOfMarkArray.position
Use array's contains method
if (blueMarkArray.contains(self.atPoint(locationUser))) {
//
}
or, if you need to check only up to index 6 like in your example, use
if (blueMarkArray[0...6].contains(self.atPoint(locationUser))) {
//
}
if you want to get the index of the element, you can use firstIndex of lastIndex methods
if let index = blueMarkArray.firstIndex(of: self.atPoint(locationUser)) {
//
}
You can use the array's method contains:
if blueMarkArray.contains(self.atPoint(locationUser)) {
print("its here")
}
You should simply use the contains method of Array, which will return true if any of the elements of the array equals self.atPoint(locationUser).
if blueMarkArray.contains(self.atPoint(locationUser)) {
print("it's here")
}
If you also need to access the element that matches the object/value you are looking for, you can use first(where:) or firstIndex(of:).
if let location = blueMarkArray.first(where: {$0 == self.atPoint(locationUser)}) {
someNode.position = location.position
}
or
if let locationIndex = blueMarkArray.firstIndex(of: self.atPoint(locationUser)) {
let location = blueMarkArray[locationIndex]
someNode.position = location.position
}

Comparing the NSLayoutAttribute in swift 3

Following code was working well with swift 2 but it is not working with swift 3.
let constraints: NSArray = contentView.constraints as NSArray
let indexOfConstraint = constraints.indexOfObject (passingTest: { (constraint, idx, stop) in
return (constraint.firstItem ).tag == bubbleTag && (constraint.firstAttribute == NSLayoutAttribute.left || constraint.firstAttribute == NSLayoutAttribute.right)
})
I am getting following error:
Binary operator '==' cannot be applied to operands of type '_' and
'NSLayoutAttribute'
I am getting this error for following line:
constraint.firstAttribute == NSLayoutAttribute.left
How can i fix it?
That error message is showing only the first error that your code may cause, and you may need some more fixes to work on it.
Assuming you are using NSArray (or NSMutableArray) for constraints, why don't you declare constraints as [NSLayoutAttribute]?
With that change, you may need to fix some other parts, but the code getting the index can be written like this:
let indexOfConstraint = constraints.index {constraint in
return constraint.firstItem.tag == bubbleTag && (constraint.firstAttribute == NSLayoutAttribute.left || constraint.firstAttribute == NSLayoutAttribute.right)
}
//indexOfConstraint becomes `Int?`, so you may need to use Optional binding
if let index = indexOfConstraint {
//Do something for found case
} else {
//Do something for not-found case
}
If you cannot change the type of constraints globally, you can put this sort of code in your local code-block just before the code above.
guard let constraints = constraints as? [NSLayoutConstraint] else {
fatalError("something wrong with `constraints`")
}
Please, check below updated code:
let constraints: NSArray = contentView.constraints as NSArray
let indexOfConstraint = constraints.indexOfObject (passingTest:){ ( constraint, idx, stop) in
return ((constraint as AnyObject).firstItem as! UIView).tag == bubbleTag && ((constraint as AnyObject).firstAttribute == NSLayoutAttribute.left || (constraint as AnyObject).firstAttribute == NSLayoutAttribute.right)
}

How to Compare Two NSStrings which contain float values? [duplicate]

This question already has answers here:
Compare version numbers in Objective-C
(15 answers)
Closed 9 years ago.
I have two strings, one contains the value "5.2.3" and another one contain a value like "5.2.32". My question is: how to compare these two strings?
if ([string1 integerValue] >= [sting2 integerValue])
{
NSLog(#"process");
}
I tried above line but not got it.
Well correct answer has been already given. Because I have spent my half an hour on it so I don't want to waste it.
-(BOOL)string:(NSString*)str1 isGreaterThanString:(NSString*)str2
{
NSArray *a1 = [str1 componentsSeparatedByString:#"."];
NSArray *a2 = [str2 componentsSeparatedByString:#"."];
NSInteger totalCount = ([a1 count] < [a2 count]) ? [a1 count] : [a2 count];
NSInteger checkCount = 0;
while (checkCount < totalCount)
{
if([a1[checkCount] integerValue] < [a2[checkCount] integerValue])
{
return NO;
}
else if([a1[checkCount] integerValue] > [a2[checkCount] integerValue])
{
return YES;
}
else
{
checkCount++;
}
}
return NO;
}
And you can call this method like this:-
if([self string:str1 isGreaterThanString:str2])
{
NSLog(#"str2 is lower than the str1");
}
else
{
NSLog(#"str1 is lower than the str2");
}
It would appear that what you have here are not really "float" values, but some kind of multi-part "number" (akin to software version numbering?) that is not going to be covered by any of the standard conversions, but will also not compare "correctly" as just simple strings.
First you need to specify exactly what your comparison rules are. For example, I suspect you want something like:
1.2 > 1.1
1.1.1 > 1.1
1.11 > 1.2
1.2.3 > 1.2.2
1.2.22 > 1.2.3
(in other words, split the string up by "."s, and do a numeric comparison on each component). You'll have to decide how you want to handle things like letters, other delimiters, etc. showing up in the input. For example is 1.0b1 > 1.01 ?
Once you settle on the rules, write a method (returning NSComparisonResult) to implement the comparison. If you want to get fancy, you can even define your comparison method in a category on NSString, so you could do things like
if ([string1 mySuperDuperCompareTo:string2] == NSOrderedAscending) {
NSLog(#"%# < %#", string1, string2);
} // ... etc ...
see also How to let the sortedArrayUsingSelector using integer to sort instead of String?
#The Tiger is correct. Sorry to misunderstood your question. I have already mark deleted as my older answer. Here is the updated one.
As there are multiple . (dots) available here is the new solution. This will check value first like 5.2.3 and 5.2.32 are there. Then,
check first value 5 - same
so check next 2 - same
check next 3 and 32 - 32 is larger
also check for the same string as well (Also one of the probability)
Here is the logic - I have not compiled but this is base idea - there might require some correction
// separate from "."
NSArray *arrString1 = [string1 componentSeparatedBy:#"."];
NSArray *arrString2 = [string1 componentSeparatedBy:#"."];
BOOL isString1Bigger = NO; // a variable to check
BOOL isString2Bigger = NO; // a variable to check
// check count to run loop accordingly
if ([arrString1 count] <= [arrString2 count]) {
for (int strVal=0; strVal<[arrString1 count]; strVal++) {
// compare strings value converted into integer format
// when you get larger then break the loop
if([[arrString1 objectAtIndex:strVal] intValue] > [[arrString2 objectAtIndex:strVal] intValue]) {
isString1Bigger = YES;
break;
}
}
if ([arrString1 count] > [arrString2 count]) {
// use arrString2 in loop and isString2Bigger as a mark
}
// if after running both the if condition still require to check if both are same or not, for that,
if ((isString1Bigger == NO) && (isString2Bigger == NO)) {
// same string values
}
There might some modification required to run over. But its the base concept to compare string value provided by you.

Get the text in string variable

I m confused with this from many days and couldn't understand how to resolve it.
I get some data from web server and assigning it to string variable.In assigning it if sometimes no data is available then that string is updated to null(NULL) and to nil(nil) sometimes to (null).So I m confused how to compare data in that variable.
if(stringvariable==NULL) // couldnot understand how to compare here ,with NULL or nil or (null)
{
// do something
}
When will the string variable change its state (to NULL or nil or (null)) ?
use this code..
if([stringvariable isEqualToString:#""] || [stringvariable isEqual:nil])
{
//Data not Found
}
else{
// Data not nil
}
You can check like
if([str length]>0 || ![str isEqualToString:#""]) {
// String is not empty
}
It should be :
if(![stringvariable isEqualToString:#""])
{
// stringvariable is not Empty.
}
else
{
// stringvariable is Empty.
}

Why Does String Not Equal What Is Stored?

This is a simple, odd question...
if(tableViewNum == #"One") {
if ([drinkArray objectAtIndex:0] == currentDate) {
[updatedArray addObject:drinkArray];
NSLog(#"MADE THE ELSE1");
}
NSLog(#"MADE THE ELSE2");
}
else if (tableViewNum == #"Two") {
if ([[drinkArray objectAtIndex:0] isEqualToString:yesterdayDate])
[updatedArray addObject:drinkArray];
} else {
NSLog(#"MADE THE ELSE %#",tableViewNum);
[updatedArray addObject:drinkArray];
}
In the very first if statement I ask if tableViewNum == #"One"
But I don't go in that section of the if statement even though tableViewNum actually does equal #"One"
As you can see the very last NSLog all ways comes out as
MADE THE ELSE One
But if tableViewNum really equaled One it would have gone through the if statement not the else statement code...?????
You can't compare strings with the == operator. Use isEqualToString instead:
if([tableViewNum isEqualToString:#"One"]) {
// etc.
… and the same for the rest of the conditions. You're already doing it right in the second block.
To be more specific, you shouldn't compare ANY objects using ==. This compares just the pointers. Use [obj isEqual: otherObj] or with NSStrings isEqualToString: as described above.