Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object is nil

I made a Class that has several NSStrings as properties. If I have an object of this class, then how can I know if the object is nil (i.e. all the NSString properties are nil).

My class looks like this

//  MyClass.h
#import <Foundation/Foundation.h>


@interface MyClass : NSObject <NSCoding> {
 NSString *string1;
 NSString *string2;

}
@property (nonatomic, retain) NSString *string1;
@property (nonatomic, retain) NSString *string2;

@end

I'm checking it like this and it doesn't work

if (SecondViewController.myObject==nil) {
 NSLog(@"the object is empty");
}
like image 910
node ninja Avatar asked Sep 20 '10 09:09

node ninja


People also ask

How can you tell if an object is empty or not?

Use Object. Object. keys will return an array, which contains the property names of the object. If the length of the array is 0 , then we know that the object is empty.

How do I check if an object is nil in Objective C?

As this answer says: Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result.

How do you check if an object is nil in Ruby?

In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).

How check object is nil or not in Swift?

In Swift, you can also use nil-coalescing operator to check whether a optional contains a value or not. It is defined as (a ?? b) . It unwraps an optional a and returns it if it contains a value, or returns a default value b if a is nil.


2 Answers

If I have an object of this class, then how can I know if the object is nil (i.e. all the NSString properties are nil).

An object is not nil just because all its properties are nil. However, if you do want to know if both the string properties of your object are nil, this will do the trick:

-(BOOL) bothStringsAreNil
{
    return [self string1] == nil && [self string2] == nil;
}

Note: I'm in the camp that doesn't like to treat pointers as booleans i.e. I prefer the above to

-(BOOL) bothStringsAreNil
{
    return ![self string1]  && ![self string2];
}

which is functionally identical.

like image 53
JeremyP Avatar answered Oct 04 '22 17:10

JeremyP


if (!obj)  
   // obj = nil

if (!obj.property)
   // property = nil

To check if all properties are nil I think it would better to create a special method in your class for that.

like image 41
Vladimir Avatar answered Oct 04 '22 17:10

Vladimir