views:

52

answers:

2

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");
}
+1  A: 
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.

Vladimir
If (!obj) doesn't work on my class. I think it only works on NS classes
awakeFromNib
if () checks whether value is false(0) or true(!=0) so it should work on any type - number, c-pointer, obj-c object... May be the object you check is just not initialized?
Vladimir
I'm using a custom class. See my edit.
awakeFromNib
@Vladimir: Instance variables are automatically set to *null / nil*.
Georg
@awakeFromNib: This answer looks correct, I think your using it in a wrong way. Can you show us the code where you are trying to check for *nil*?
Georg
@George, instances - YES, but one of the reasons check mail fail on a custom object (not iVar) is is it is not initialized - awakeFromNib wrote that If (!obj) does not work
Vladimir
I edited my answer to show how I check the object.
awakeFromNib
+2  A: 

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.

JeremyP