如何检查对象是否为nil [英] How to check if an object is nil

查看:127
本文介绍了如何检查对象是否为nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含多个NSStrings作为属性的类。如果我有一个这个类的对象,那么我怎么知道对象是否为nil(即所有的NSString属性都是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).

我的类看起来像这样

//  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



我会像这样检查它, t work

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

if (SecondViewController.myObject==nil) {
 NSLog(@"the object is empty");
}


推荐答案


如果我有一个这个类的对象,那么我怎么知道对象是否为nil(即所有的NSString属性都为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).

一个对象不是nil,因为它的所有属性都是nil。但是,如果你想知道你的对象的字符串属性是否为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];
}

功能相同。

这篇关于如何检查对象是否为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆