IOS判断NSArray是否为空

时间:2022-05-26 04:28:01

场景描述:判断一个集合是否为空,如果不为空执行A,如果为空执行B

Java实现方法

public void exec(){
List<String> list = this.getContent();
if (null != list && list.size()>0) {
//do something
}else{
//do nothing
}
}

IOS如何实现?先看下下面代码执行结果

- (void)viewDidLoad
{
[super viewDidLoad]; NSArray *ary ;
[self show:ary]; ary = nil;
[self show:ary]; ary = [[NSArray alloc]init];
[self show:ary]; ary = [NSMutableArray arrayWithObjects:@"11111", @"222",nil];
[self show:ary];
}
-(void) show:(NSArray *)ary{
NSLog(@"数组内容:%@",ary);
NSLog(@"数组class:%@",[ary class]); if (![ary isKindOfClass:[NSNull class]]) {
NSLog(@"NOT!!! isKindOfClass null");
}else{
NSLog(@"isKindOfClass null");
}
if (ary) {
NSLog(@"====非空=====");
}else{
NSLog(@"====空=====");
}
if (ary.count == 0) {
NSLog(@"count is 0");
}else{
NSLog(@"count is %lu",(unsigned long)ary.count);
}
NSLog(@"=====================华丽的分割线=======================");
}

执行结果如下:

2014-07-29 15:51:55.209 MyTempTest[297:60b]数组内容:(null)

2014-07-29 15:51:55.211 MyTempTest[297:60b]数组class(null)

2014-07-29 15:51:55.212 MyTempTest[297:60b] NOT!!!   isKindOfClass null

2014-07-29 15:51:55.213 MyTempTest[297:60b] =========

2014-07-29 15:51:55.215 MyTempTest[297:60b] count is 0

2014-07-29 15:51:55.216 MyTempTest[297:60b] =====================华丽的分割线=======================

2014-07-29 15:51:55.217 MyTempTest[297:60b]数组内容:(null)

2014-07-29 15:51:55.218 MyTempTest[297:60b]数组class(null)

2014-07-29 15:51:55.219 MyTempTest[297:60b] NOT!!!   isKindOfClass null

2014-07-29 15:51:55.220 MyTempTest[297:60b] =========

2014-07-29 15:51:55.221 MyTempTest[297:60b] count is 0

2014-07-29 15:51:55.222 MyTempTest[297:60b] =====================华丽的分割线=======================



2014-07-29 15:51:55.223 MyTempTest[297:60b]数组内容:(

)

2014-07-29 15:51:55.225 MyTempTest[297:60b]数组class__NSArrayI

2014-07-29 15:51:55.226 MyTempTest[297:60b] NOT!!!   isKindOfClass null

2014-07-29 15:51:55.227 MyTempTest[297:60b] ====非空=====

2014-07-29 15:51:55.228 MyTempTest[297:60b] count is 0

2014-07-29 15:51:55.229 MyTempTest[297:60b] =====================华丽的分割线=======================



2014-07-29 15:51:55.230 MyTempTest[297:60b]数组内容:(

    11111,

    222

)

2014-07-29 15:51:55.231 MyTempTest[297:60b]数组class__NSArrayM

2014-07-29 15:51:55.232 MyTempTest[297:60b] NOT!!!   isKindOfClass null

2014-07-29 15:51:55.233 MyTempTest[297:60b] ====非空=====

2014-07-29 15:51:55.234 MyTempTest[297:60b] count is 2

2014-07-29 15:51:55.235 MyTempTest[297:60b] =====================华丽的分割线=======================

结论:IOS判断一个数组是否为空,直接判断“ary.count”即可,即使ary尚未初始化也不会报“空指针”。

NSString *str ;
NSLog(@"%lu",(unsigned long)str.length);

2014-07-30 08:40:52.851 MyTempTest[391:60b] 0

objective-c里面声明一个类型,未初始化,直接调用方法都不报错?