A9628298AF2F97B5E073C680D9D5DC85 Apps King Technologies: Literal Syntax in Objective-C

Tuesday 25 February 2014

Literal Syntax in Objective-C


Literal Syntax

Objective-C also offers a literal syntax for dictionary creation, like this:
    NSDictionary *dictionary = @{

                  @"anObject" : someObject,

               @"helloString" : @"Hello, World!",

               @"magicNumber" : @42,

                    @"aValue" : someValue

    };

Note that for dictionary literals, the key is specified before its object and is not nil-terminated.

Querying Dictionaries
Once you’ve created a dictionary, you can ask it for the object stored against a given key, like this:
    NSNumber *storedNumber = [dictionary objectForKey:@"magicNumber"];

If the object isn’t found, the objectForKey: method will return nil.
There’s also a subscript syntax alternative to using objectForKey:, which looks like this:
    NSNumber *storedNumber = dictionary[@"magicNumber"];


Mutability
If you need to add or remove objects from a dictionary after creation, you need to use theNSMutableDictionary subclass, like this:
    [dictionary setObject:@"another string" forKey:@"secondString"];

    [dictionary removeObjectForKey:@"anObject"];

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", @42, [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");

        }

    }



No comments:

Post a Comment