如何检查NSMutableArray元素是NSNull还是AnyObject [英] how to check if NSMutableArray element is NSNull or AnyObject

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

问题描述

我有一个 PersonsArray:NSMutableArray = [NSNull,NSNull,NSNUll,NSNull,NSNull,NSNUll,NSNull] 。我需要七个插槽,然后可以将它们作为Entity CoreData条目填充为AnyObject。

I have a PersonsArray: NSMutableArray = [NSNull, NSNull, NSNUll, NSNull, NSNull, NSNUll, NSNull]. I needed seven slots that I then can fill with an Entity CoreData entry as AnyObject.

我需要在此NSMutableArray上进行for in循环...

I need to do a for in loop on this NSMutableArray...

如果索引槽是NSNull,我想传递到下一个索引槽,如果索引槽中充满了我的对象,我想在该对象上执行代码。

If the index slot is NSNull I want to pass to next index slot, if index slot is filled with my Object I want to execute code on this Object.

example PersonsArray: NSMutableArray = [
    NSNull,
    NSNull,
    NSNull,
    "<iswift.Person: 0x7f93d95d6ce0> (entity: Person; id: 0xd000000000080000 <x-coredata://8DD0B78C-C624-4808-9231-1CB419EF8B50/Person/p2> ; data: {\n    image = nil;\n    name = dustin;\n})",
    NSNull,
    NSNull,
    NSNull
]

尝试

for index in 0..<PersonsArray.count {
        if PersonsArray[index] != NSNull {println(index)}
}

建议一堆也不起作用的更改,例如

suggests a bunch of changes that don't work either, like

if PersonsArray[index] as! NSNull != NSNull.self {println(index)}

if PersonsArray[index] as! NSNull != NSNull() {println(index)}






注意:使用NSNull只是NSMutableArray中的占位符,因此其计数始终为7,我可以用Object替换任何(7)插槽。我应该使用NSNull以外的其他东西作为占位符吗?


NOTE: using NSNull is just a placeholder in NSMutableArray so that its count is ALWAYS 7 and I can replace any of the (7)slots with an Object. Should I be using something other than NSNull as my placeholder?

推荐答案

NSNull()是一个单例对象,因此您可以简单地测试数组元素
是否为 NSNull 的实例:

NSNull() is a singleton object, therefore you can simply test if the array element is an instance of NSNull:

if personsArray[index] is NSNull { ... }

或使用 identical to运算符:

or use the "identical to" operator:

if personsArray[index] === NSNull() { ... }

或者,您可以使用一系列可选项:

Alternatively, you could use an array of optionals:

let personsArray = [Person?](count: 7, repeatedValue: nil)
// or more verbosely:
let personsArray : [Person?] = [ nil, nil, nil, nil, nil, nil, nil ]

nil 表示空插槽。

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

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