Represent nil with NSNull

时间:2023-03-09 15:32:45
Represent nil with NSNull

Represent nil with NSNull

  It’s not possible to add nil to the collection classes described in this section because nil in Objective-C means “no object.” If you need to represent “no object” in a collection, you can use the NSNull class:

 NSArray *array = @[ @"string", @, [NSNull null] ];

  NSNull is a singleton class, which means that the null method will always return the same instance. This means that you can check whether an object in an array is equal to the shared NSNull instance:

 for (id object in array) {
if (object == [NSNull null]) {
NSLog(@"Found a null object");
}
}

Working with Blocks

  Blocks can also take arguments and return values just like methods and functions.As an example, consider a variable to refer to a block that returns the result of multiplying two values:

 double (^multiplyTwoValues)(double, double);

  The corresponding block literal might look like this:

    ^ (double firstValue, double secondValue) {
return firstValue * secondValue;
}

  The firstValue and secondValue are used to refer to the values supplied when the block is invoked, just like any function definition. In this example, the return type is inferred from the return statement inside the block.

  If you prefer, you can make the return type explicit by specifying it between the caret and the argument list:

     ^ double (double firstValue, double secondValue) {
return firstValue * secondValue;
}

  Once you’ve declared and defined the block, you can invoke it just like you would a function:

     double (^multiplyTwoValues)(double, double) =
^(double firstValue, double secondValue) {
return firstValue * secondValue;
}; double result = multiplyTwoValues(,); NSLog(@"The result is %f", result);

Use __block Variables to Share Storage

  If you need to be able to change the value of a captured variable from within a block, you can use the __block storage type modifier on the original variable declaration. This means that the variable lives in storage that is shared between the lexical scope of the original variable and any blocks declared within that scope.

     __block int anInteger = ;

     void (^testBlock)(void) = ^{
NSLog(@"Integer is: %i", anInteger);
}; anInteger = ; testBlock();

  Because anInteger is declared as a __block variable, its storage is shared with the block declaration. This means that the log output would now show:

 Integer is: 

  It also means that the block can modify the original value, like this:

     __block int anInteger = ;

     void (^testBlock)(void) = ^{
NSLog(@"Integer is: %i", anInteger);
anInteger = ;
}; testBlock();
NSLog(@"Value of original variable is now: %i", anInteger);

  This time, the output would show:

 Integer is:
Value of original variable is now: