With just a few lines of code, you can read/write collections to/from files. The code below shows examples for writing and reading both NSArray and NSDictionary objects, the same logic would apply to an NSSet (or other collection type).
Boxed expressions allow values to be interpreted before assigning to an object when using literals with Objective-C (see the end of post for links to more information). It’s not as confusing as it sounds, let’s look at a few examples:
The code below shows how to used a boxed expression to create a NSNumber object, calculated by multiplying to values:
#define SECONDS_PER_MINUTE 60 int minuteCount = 50; NSNumber *howManySeconds_NonBoxed = [NSNumber numberWithInt: (minuteCount * SECONDS_PER_MINUTE )]; NSNumber *howManySeconds_Boxed = @(minuteCount * SECONDS_PER_MINUTE); NSLog(@"Total seconds: %@", howManySeconds_Boxed);
Here’s a quick code check for ARC (Automatic Reference Counting):
#if __has_feature(objc_arc) // ARC #else // No ARC #endif
I previously wrote about C ternary operatar which provides an opportunity to write code that is “short-hand” if you will. A ternary operator is one that accepts three arguments, more on this below.
This is the traditional form of an if/else:
int x = 5; ... if (x > 1) y = x; else y = -1;
And here is a version using the ternary operators:
int y = x > 1 ? x : -1;
Following is a few lines of Objective-C code to quickly traverse a directory and all of its subdirectories.
Let’s start with a file structure in the Documents directory that I used for my example:
The example I am writing is using the simulator, thus the folder structure shown above is from my Mac. However, the same applies regardless of the platform.
Before we get started, a quick note, to use literals you will need to be running Xcode 4.4 or greater as well as the Apple LLVM compiler 4.0 or greater.
As with NSString objects, which allow definition using literal syntax:
NSString *str = @"Some string";
you can now create NSDictionary objects using literals. A range of examples follow, showing the old style definition as well as the new literal syntax:
Last week I wrote about NSArray Literals in Objective-C. This week I will show you how to use NSNumber literals. To use literals, you will need to be running Xcode 4.4 or greater as well as the Apple LLVM compiler 4.0 or greater.
Just as a string literal is prefixed with an ‘@’ symbol:
NSString *str = @"This is a string";
you can now create NSNumber objects using literals. A range of examples follow, showing the old style definition as well as the new literal syntax: