Kex
Kex

Reputation: 8579

NSMutableDictionary keys pointing to nothing

I have an NSMutableDictionary of NSArrays. Some of the keys I actually want to point to nothing. Right now I am using NSArray *someArray=[[NSArray alloc] init]; to represent nothing, i.e. an empty array. Is there a better way to do this?

Upvotes: 0

Views: 43

Answers (3)

w4th
w4th

Reputation: 53

You should use NSNull to represent nothing in the NSDictionary.

That having been said, wouldn't it just be easier not to assign keys until you have the object for them? If you assign NSNull you'll need to test for equality with NSNull, since testing for yourDictionary[@"nullKey"] will always return YES, since it does indeed have an object assigned to it. On the other hand, if you test an unassigned key, you'll get back nil, which is probably what you want.

Upvotes: 1

Grady Player
Grady Player

Reputation: 14549

you can use @[] for an empty array, you can also represent an empty value in a collection class with [NSNull null] it all depends on the semantics you are looking for.

I tend to think that @[] is a little more predictable, because you can use all of the things you would expect, iteration, -(NSUInteger)count etc..

to check for nulls you have to explicitly check... dict["key"] == [NSNull null] because even [NSNull null] is boolean true, because it is an object...

for instance this doesn't work:

for (NSString *s in [NSNull null])
{
    printf("you will never get here!");
}

nor will this:

id obj = [NSNull null];
[obj length];

printf("you wont get here");

so it really depends on how you want to build your flow control, because if you concerned with keys existing and not, and the values, you are in 3 state logic...

USING NSNULL

if(!dict[somekey])
{
    //key not set
}else if (dict[somekey] == [NSNull null])
{
    //key set, but null
}else
{
    // should expect a real value
}

USING EMPTY ARRAY

if(!dict[somekey])
{
    //key not set
}else if (![dict[somekey] count])
{
    //key set, but empty array
}else
{
    // should expect a real value
}

Upvotes: 0

Ben Zotto
Ben Zotto

Reputation: 70998

You can use the singleton instance of NSNull which is designed for situations like this:

dict[@"key"] = [NSNull null];

(It's just a placeholder object that the frameworks provide to be used in collections that don't accept nil values. Not to be confused with an actual nil, of course)

Upvotes: 1

Related Questions