Ser Pounce
Ser Pounce

Reputation: 14557

Possible to init NSArray with empty values?

I have the following array which normally contains CGColor's:

_strokeColors = [[NSArray alloc] initWithObjects:NULL,NULL,NULL,NULL, nil];

I have some other arrays that run parallel with this array (i.e. _fillColors, _mutuablePaths) that have the same amount of values. I loop through all these arrays to check for data, and in this particular instance all of the _strokeColors have to be NULL. However, I notice that the above array has a size of 0.

What is the pattern for initializing an array like this that needs to read NULL for every value?

Upvotes: 1

Views: 5472

Answers (4)

Monolo
Monolo

Reputation: 18253

In Cocoa, NULL is not really used, but usually reserved for those cases where standard C pointers are employed.

Since Objective-C is also C, this is of course just a convention, but a useful one - it allows you to set an NSString* pointer to nil, and a char* or void* pointer to NULL, and notice the difference at a glance.

Further, in Cocoa, collections (arrays, dictionaries, sets) can't hold nil values, so as other posters have noted, you have to use a placeholder, namely [NSNull null].

But notice that [NSNull null] is just that, a placeholder, and since collections can only hold objects, this placeholder is also a standard Objective-C object.

Hence, you need to test properly for it if you use it in conditional statements, for instance:

id myVar = [NSNull null];

// Stuff...

if ( myVar == [NSNull null] ) {
     // myVar has not been changed, do something
}

This is different from the standard C idiom, where you can test a NULL value directly in the conditional statement:

void *myPointer = NULL;

// Stuff...

if ( myPointer ) {
    // More stuff if pointer uninitialized
}

You might also wonder why it is suddenly all right to test a variable for equality with [NSNull null] using the == operator? That is because [NSNull null] is a singleton, guaranteed to have always the same position in memory (which is what == tests in this case). Don't do this with normal objects.

More about it in the docs.

Upvotes: 3

Shashi Sharma
Shashi Sharma

Reputation: 126

Try This Method -

_strokeColors = [[NSArray alloc] initWithObjects:[NSNull null],[NSNull null],[NSNull null],[NSNull null], nil];

Upvotes: 1

Ravi Raman
Ravi Raman

Reputation: 1070

This should work for you:

_strokeColors = [[NSArray alloc] initWithObjects:[NSNull null],[NSNull null],[NSNull null],[NSNull null], nil];

You can only store object types in an array or any other collection.

NULL, is actually not an object. Hence, you will have to make it as an object type by using : [NSNull null]

Upvotes: 3

Ankit Srivastava
Ankit Srivastava

Reputation: 12405

_strokeColors = [[NSArray alloc] initWithObjects:[NSNull null],[NSNull null],[NSNull null],[NSNull null], nil];

should do the trick.

Upvotes: 10

Related Questions