2015-04-29 65 views
2

我有一个PersonsArray: NSMutableArray = [NSNull, NSNull, NSNUll, NSNull, NSNull, NSNUll, NSNull]。我需要七个插槽,然后我可以使用AnyObject填充Entity CoreData条目。如何检查NSMutableArray元素是NSNull还是AnyObject

我需要为这个NSMutableArray的循环做...

如果索引插槽NSNull我想传递给下一个索引插槽,如果指数位中填充了我的对象我想执行代码在这个对象上。


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

表明了一堆的变化没有任何工作,如

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

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

注意:使用NSNull只是NSMutableArray中的一个占位符,因此它的计数总是为7,我可以用一个对象替换任何(7)插槽。我应该使用非NSNull作为占位符吗?

+0

'NSNull'可能定义为始终从任何'=='或'!='比较中返回'false'。在大多数地方,这是多么的无效...... – nhgrif

回答

5

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

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

或使用“等同于”操作符:

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

替代地,您可以使用一系列可选项:

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

使用nil作为空插槽。

+0

即使它不是一个单独的对象,'NSNull'也不会工作吗?难道不是因为它是一个单一对象,'==='可能会起作用(比较引用?)。 – nhgrif

+0

因为它是一个单例,所以你可以测试数组元素'== [NSNull null]'(在Objective-C中)。 –

+0

@HotLicks Objective-C的'== [NSNull null]'是一个参考比较。在Swift中'=='更像是在Objective-C中执行'isEqual:[NSNull null]]',但'==='是Swift的参考比较。 – nhgrif