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");
}
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.
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With