Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Foundation Framework

NSNumber, NSValue, NSData and Dates

Box numbers in NSNumber and structs in NSValue, handle raw bytes with NSData, and work with NSDate, NSCalendar, NSDateComponents and formatters in Objective-C, with C stand-ins.

Objective-C collections hold objects, but much real data is not objects: integers, floating-point numbers, booleans, structs, raw bytes, moments in time. Foundation provides wrapper classes for each: NSNumber and NSValue box primitives, NSData holds bytes, and NSDate with its helpers represents time. This lesson shows how to move data in and out of these objects and how to format it for people.

NSNumber: boxing primitives

NSNumber wraps a BOOL, any integer type or any floating-point type in an object, so it can live in an array or dictionary.

OBJECTIVEC
NSNumber *age    = @36;            // literal: int
NSNumber *pi     = @3.14159;       // double
NSNumber *yes    = @YES;           // BOOL
NSNumber *big    = @9000000000LL;  // long long
NSNumber *letter = @'A';           // char

int n = [age intValue];
double d = [pi doubleValue];
BOOL b = [yes boolValue];

int local = 7;
NSNumber *boxed = @(local);        // box any expression with @( )
NSNumber *calc  = @(2 * 21);       // 42

Compare numbers with isEqualToNumber: or compare:, never ==. Reading a value with a different accessor than it was stored with converts it ([@3.9 intValue] is 3), so keep track of what you boxed. A box is immutable.

NSValue: boxing structs

NSValue wraps any C value, and has convenience methods for common Foundation structs:

OBJECTIVEC
NSValue *range = [NSValue valueWithRange:NSMakeRange(3, 5)];
NSRange back = [range rangeValue];

typedef struct { double x, y; } Point;
Point p = {1.5, 2.5};
NSValue *wrapped = [NSValue valueWithBytes:&p objCType:@encode(Point)];
Point q;
[wrapped getValue:&q];

@encode() generates the type description string the runtime uses to know the layout.

What boxing is

Boxing stores a value together with a type tag so it can be treated like any other object. The stand-in below builds a tiny Number box as a tagged union, converts between kinds, and puts mixed boxes in one array.

C Stand-in: NSNumber as a tagged union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

NSData and NSMutableData

NSData is an immutable block of bytes, used for file contents, network payloads, images and encoded text.

OBJECTIVEC
NSData *data = [@"Hello" dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger length = data.length;                        // 5
const uint8_t *bytes = data.bytes;                      // pointer to the first byte
NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSData *fromFile = [NSData dataWithContentsOfFile:@"/tmp/photo.jpg"];
BOOL ok = [data writeToFile:@"/tmp/out.bin" atomically:YES];
NSData *piece = [data subdataWithRange:NSMakeRange(1, 3)];

NSMutableData *buffer = [NSMutableData data];
uint16_t header = 0xCAFE;
[buffer appendBytes:&header length:sizeof(header)];
[buffer appendData:data];

Related useful calls: base64EncodedStringWithOptions: for Base64, and NSJSONSerialization (see files and JSON) which reads and writes JSON from NSData.

The C equivalent is a pointer and a length, and NSData is exactly that pair with safe lifetime management:

C Stand-in: a byte buffer with length and hex dump

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

NSDate: a moment in time

An NSDate is a point in time stored as seconds since the reference date (1 January 2001 UTC). It has no time zone and no calendar. Those belong to the code that displays it.

OBJECTIVEC
NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTimeInterval:24 * 60 * 60];   // NSTimeInterval is seconds (double)
NSTimeInterval diff = [tomorrow timeIntervalSinceDate:now];       // 86400
NSTimeInterval unix = [now timeIntervalSince1970];
BOOL later = [tomorrow compare:now] == NSOrderedDescending;

Adding 86,400 seconds is wrong for "the same time tomorrow" across daylight-saving changes, which is what a calendar is for.

Calendars and components

OBJECTIVEC
NSCalendar *cal = [NSCalendar currentCalendar];

NSDateComponents *c = [cal components:(NSCalendarUnitYear | NSCalendarUnitMonth |
                                       NSCalendarUnitDay | NSCalendarUnitWeekday)
                             fromDate:now];
NSLog(@"%ld-%02ld-%02ld, weekday %ld", (long)c.year, (long)c.month, (long)c.day, (long)c.weekday);

NSDateComponents *plus = [[NSDateComponents alloc] init];
plus.month = 1;
NSDate *nextMonth = [cal dateByAddingComponents:plus toDate:now options:0];   // calendar-aware

NSDateComponents *birthday = [[NSDateComponents alloc] init];
birthday.year = 1990; birthday.month = 12; birthday.day = 10;
NSDate *born = [cal dateFromComponents:birthday];

Formatting dates for display and parsing

OBJECTIVEC
NSDateFormatter *f = [[NSDateFormatter alloc] init];
f.dateStyle = NSDateFormatterMediumStyle;       // locale-aware: "Dec 10, 1990" or "10 dรฉc. 1990"
f.timeStyle = NSDateFormatterShortStyle;
NSString *display = [f stringFromDate:now];

NSDateFormatter *iso = [[NSDateFormatter alloc] init];
iso.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];   // for fixed formats
iso.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
iso.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ";
NSDate *parsed = [iso dateFromString:@"2025-03-14T09:26:53Z"];

Use styles for text shown to people, and a fixed dateFormat with the POSIX locale for parsing machine formats. Creating formatters is expensive, so cache them. Use NSNumberFormatter the same way for currencies and percentages.

Time arithmetic from first principles

Dates reduce to a count of seconds. The stand-in below converts a fixed Unix timestamp to calendar fields in UTC, adds a number of days, and computes the difference, using only the C library with timegm-free arithmetic so the output is deterministic.

C Stand-in: a date is a number of seconds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you box the result of 2 * 21 as an NSNumber?

    Boxed expressions use the @( ) syntax.
  2. 2. What does an NSDate represent?

    An NSDate is an absolute moment; calendars and formatters give it meaning.
  3. 3. Why use NSCalendar instead of adding 86,400 seconds for 'tomorrow'?

    Calendar arithmetic handles DST changes and varying month lengths.
  4. 4. Which locale is recommended when parsing fixed machine date formats?

    en_US_POSIX gives stable parsing regardless of the user's regional settings.

Summary

  • NSNumber boxes primitives with @42, @(expr); NSValue boxes structs; compare boxes with isEqualToNumber:.
  • NSData is a byte buffer; convert text with encodings.
  • NSDate is an absolute time; use NSCalendar and NSDateComponents for calendar math.
  • Use NSDateFormatter styles for display and POSIX-locale formats for parsing, and cache formatters.

Next: NSError, Files and JSON