verifique se NSNumber está vazio
Como verifico se um objeto NSNumber está nulo ou vazio?
OK nada é fácil:
NSNumber *myNumber;
if (myNumber == nil)
doSomething
Mas se o objeto foi criado, mas não há valor porque uma atribuição falhou, como posso verificar isso? Use algo assim?
if ([myNumber intValue]==0)
doSomething
Existe um método geral para testar objetos no vazio, como o NSString disponível (consulte estepostar)?
Exemplo 1
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:@"" forKey:@"emptyValue"];
NSNumber *emptyNumber = [dict objectForKey:@"emptyValue"];
Qual valor fazemptyNumber
conter? Como posso verificar seemptyNumber
está vazia?
Exemplo 2
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:@"" forKey:@"emptyValue"];
NSString *myString = [dict objectForKey:@"emptyValue"];
if (myString == nil || [myString length] == 0)
// got an empty value
NSNumber *emptyNumber=nil;
O que acontece se eu usar isso depoisemptyNumber
foi definido como nulo?
[emptyNumber intValue]
Eu recebo zero?
Exemplo 3
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:@"" forKey:@"emptyValue"];
NSNumber *myEmptyValue = [dict objectForKey:@"emptyValue"];
if (myEmptyValue == nil)
// NSLog is never called
NSLog(@"It is empty!");
Assim, o NSLog nunca é chamado.myEmptyValue
não énil
e nãoNSNull
. Portanto, ele contém um número arbitrário?