iKK
iKK

Reputation: 7012

Storing new objects of various datatypes in an NSDictionary

The Realm migration example on the Realm documentation site shows an example with a new NSString object. The example is simple and well explained.

if (oldSchemaVersion < 2) {
    newObject[@"email"] = @"";  // creates an NSString object...
}

But what about objects other than NSString? How does the code snippet need to be adapted in order to create objects of these other data types?

Upvotes: 0

Views: 374

Answers (2)

yoshyosh
yoshyosh

Reputation: 14086

The best way to think of it is just as if you were to create an Object in memory in your code. @"" is short form for NSString but you could use [NSString stringWithFormat:@""] as well

Upvotes: -1

jscs
jscs

Reputation: 64002

Only certain types of object in ObjC/Cocoa have a literal shortcut like this. (Historically, NSString was in fact the sole class with such syntax, but several were added recently-ish by the Clang compiler.)

There is no literal syntax for NSDate, NSData, or RLMArray; these need to be created with an appropriate construction method.

Primitive types like double, long, and BOOL cannot be stored directly in an NSDictionary, but they can be wrapped up using the "sugar" @(), i.e.:

newObject[@"numFrobs"] = @(anInteger);

This puts the value into an NSNumber instance, which then needs to be unwrapped to retrieve the primitive value:

NSInteger numFrobs = [newObject[@"numFrobs"] integerValue];

Upvotes: 3

Related Questions