NSNumber and NSString in Objective-C

Filed Under: iOS

In this tutorial we’ll discuss NSNumber and NSString data types used in Objective-C. The Foundation Framework defines several classes that provide the standard, object-oriented data structures found in other high level languages


We can’t use primitive data types like int and float directly in Foundation classes. For that NSNumber is used as an object wrapper for these primitives. It’s main job is to store and retrieve primitive values to and from the box. The NSNumber version of BOOL’s, char’s, int’s and double’s can all be created by simply prefixing the corresponding primitive type with the @ symbol; however, unsigned int’s, long’s, and float’s must be appended with the U, L, or F modifiers, as shown below.

NSNumber *aBool = @NO;
NSNumber *aChar = @'z';
NSNumber *anInt = @2147483647;
NSNumber *aUInt = @4294967295U;
NSNumber *aLong = @9223372036854775807L;
NSNumber *aFloat = @26.99F;
NSNumber *aDouble = @26.99;

It’s possible to box arbitrary C expressions using the @() syntax hence allowing us to convert basic arithmetic calculations in NSNumber objects as shown below :

double x = 24.0;
NSNumber *result = @(x * .15);
NSLog(@"%.2f", [result doubleValue]);

In the above code doubleValue is a dedicated method to return the primitive datatype from the NSNumber type.

It’s not possible to change its associated value of NSNumber after we create it. They are immutable. In this sense, an NSNumber instance acts exactly like a primitive value. When we need a new double value, we create a new literal and don’t change an existing one.

Comparing Numbers

In general, Objective-C has two types of comparison methods :

  • Pointer comparison uses the == operator to see if two pointers refer to the same memory address (i.e., the same object). It’s not possible for different objects to compare equal with this kind of comparison
  • Value comparison uses methods like isEqualToNumber: to see if two objects represent the same value. It is possible for different objects to compare equal with this kind of comparison

The below snippet shows one such example to compare two NSNumbers :

NSNumber *anInt = @27;
NSNumber *sameInt = @27U;
// Pointer comparison (fails)
if (anInt == sameInt) {
    NSLog(@"They are the same object");
// Value comparison (succeeds)
if ([anInt isEqualToNumber:sameInt]) {
    NSLog(@"They are the same value");

isEqualToNumber: guarantees that two values will compare equal, even if they are stored in different objects.


Like NSNumber, NSString is also immutable type. It’s used to represent text in Objective-C. NSString provides built-in support for Unicode, which means that we can include UTF-8 characters directly in string literals.
The most basic way in which NSString object is represented is shown below :

NSString *sample = @"iOS Tutorials";

stringWithFormat: class method is useful for generating strings that are composed of variable values. It takes the same kind of format string as NSLog(). Try the following snippet in a new empty project!

NSString *message = [NSString stringWithFormat:@"That's a %@ %@ from %d!",
                     make, model, year];
NSLog(@"%@", message);

Comparing Strings

String comparisons are similar to NSNumber Comparison except the fact that isEqualToString: method is used. For partial comparisons hasPrefix: and hasSuffix: are used.

NSString *name = @"Programming Language";
if ([name isEqualToString:@"Programming Language"]) {
    NSLog(@"The name string holds the text Programming Language");
if ([name hasPrefix:@"Programming"]) {
    NSLog(@"The first name of the word is Programming");
if ([name hasSuffix:@"Language"]) {
    NSLog(@"The second name of the word is Language");

A compare: method is used for alphabetically sorting strings as shown in the example below:

NSString *otherName = @"Objective-C";
NSComparisonResult result = [name compare:otherName];
if (result == NSOrderedAscending) {
    NSLog(@"The letter 'P' comes before 'O'");
} else if (result == NSOrderedSame) {
    NSLog(@"We're comparing the same string");
} else if (result == NSOrderedDescending) {
    NSLog(@"The letter 'P' comes after 'O'");

In the above snippet we’ve displayed the three types of return values and their description as shown below :

  • NSOrderedAscending : receiver < argument
  • NSOrderedSame : receiver == argument
  • NSOrderedDescending : receiver > argument

Combining Strings

NSString *first = @"First Name";
NSString *second = @"Second Name";
NSString *result = [first stringByAppendingString:second];
NSLog(@"%@", result);        // First NameSecond Name
result = [first stringByAppendingFormat:@" %@", second];
NSLog(@"%@", result);        // First Name Second Name (note the space)

Searching Strings

NSString’s search methods return an NSRange struct, which consists of a location and a length field. The location is the index of the beginning of the match, and the length is the number of characters in the match. If no match is found, location will contain NSNotFound.

NSString *text = @"Maserati GranCabrio";
NSRange searchResult = ;
if (searchResult.location == NSNotFound) {
    NSLog(@"Search string was not found");
} else {
    NSLog(@"'Cabrio' starts at index %lu and is %lu characters long",
          searchResult.location,        // 13
          searchResult.length);         // 6

We’ve used a random string in the above example and the starting index and the length of the substring matched is printed in the NSLog.(We’ve shown that result in the comments. You can try the example in an XCode Project.


The NSMutableString class is a mutable version of NSString. Unlike immutable strings, it’s possible to alter individual characters of a mutable string without creating a new object. The methods discussed above are applicable in NSMutableString too. Although some methods such as stringByAppendingString: will still return a NSString object—not an NSMutableString.

Creating Mutable Strings

stringWithString is used to create a NSMutableString from a literal or an existing NSString object.

NSMutableString *result = [NSMutableString stringWithString:@"Mutable String Text"];

The setString: method lets us assign a new value to the instance as follows :

[result setString:@"Modified String"];

This brings an end to this tutorial. Our aim was to give a brief overview of NSNumber and NSString Data Types. There are plenty of methods that we’ll discuss is the series of iOS Tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content