开发者

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");
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜