Open In App

Foundation Framework in Objective-C

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Foundation framework is the basic foundation for your applications. It contains fundamental components, which are meant to serve as guidelines. The Foundation library of the Foundation framework creates common data types for you that you frequently use. The String, Files, Date, Timer, Thread, and other such available objects are found here. The Toolkit Basis together with more activities frequently offers all possible amenities for using these things such as memory management, serialization, localization, and networking. This article focuses on discussing the Foundation Framework in detail.

Types and Subtypes of Foundation Framework

The table below displays the major stages and their particular variations based on the network model by the Foundation.

Type Subtype Description
Classes NSObject This class is the root type of almost all Objective-C classes. Prefers providing behavior and interface essentials to objects.
Classes NSNumber We will create a class which is a number of the types of primitive types, such as int, float, double, bool, etc.
Classes NSString An Object class that takes characters in a Unicode string. Strings are created, modified, compared, and searched with implemented methods.
Classes NSArray A class , which creates a sequential ordering of objects. Introduces the ways of making, retrieving data from, and even editing arrays to be performed with a single command.
Classes NSDictionary The class of an unordered collection of key-value pairs, the pair container. People learn how to develop dictionaries, or dictionaries that can be accessed, modified or iterated.
Classes NSSet A class that represents an unordered collection of distinct objects. Provides methods for creating, accessing, modifying, and iterating over sets.
Classes NSData A class that represents a collection of bytes. Provides methods for creating, accessing, modifying, and converting data.
Classes NSDate A class that represents a point in time. Provides methods for creating, comparing, and manipulating dates.
Classes NSTimer A class that represents a timer that fires after a certain interval. Provides methods for creating, scheduling, and invalidating timers.
Classes NSThread A class that represents a thread of execution. Provides methods for creating, managing, and synchronizing threads.
Classes NSFileHandle A class that represents a file or a socket. Provides methods for reading, writing, and seeking data.
Classes NSFileManager A class that provides access to the file system. Provides methods for creating, moving, copying, deleting, and enumerating files and directories.
Classes NSUserDefaults A class that provides access to the user defaults system. Provides methods for storing and retrieving user preferences and settings.
Classes NSNotification A class that represents a message that is broadcast to interested observers. Provides methods for creating and posting notifications.
Classes NSNotificationCenter A class that manages the notification system. Provides methods for registering and unregistering observers, and sending and receiving notifications.
Protocols NSCopying A protocol that defines a method for creating a copy of an object. Any class that wants to support copying must adopt this protocol and implement this method.
Protocols NSCoding A protocol that defines methods for encoding and decoding objects. Any class that wants to support archiving and unarchiving must adopt this protocol and implement these methods.
Protocols NSLocking A protocol that defines methods for locking and unlocking objects. Any class that wants to provide thread synchronization must adopt this protocol and implement these methods.
Protocols NSFastEnumeration A protocol that defines a method for enumerating over a collection of objects. Any class that wants to support fast enumeration must adopt this protocol and implement this method.
Categories NSString+NSPathUtilities A category that adds methods to the NSString class for working with file paths. Provides methods for creating, manipulating, and extracting components of file paths.
Categories NSArray+NSPredicate A category that adds methods to the NSArray class for filtering and sorting arrays using predicates and sort descriptors. Provides methods for creating, applying, and evaluating predicates and sort descriptors.
Categories NSObject+NSKeyValueCoding A category that adds methods to the NSObject class for accessing and modifying the properties of an object using key-value coding. Provides methods for getting, setting, and validating values for keys.
Functions NSLog A function that prints a formatted message to the standard output or the console. Useful for debugging and logging purposes.
Functions NSMakeRange A function that creates and returns an NSRange structure that represents a range of values. Useful for working with strings, arrays, and other collections.
Functions NSClassFromString A function that returns the Class object that corresponds to a given string. Useful for creating objects dynamically.
Functions NSSelectorFromString A function that returns the SEL object that corresponds to a given string. Useful for creating selectors dynamically.
Functions NSHomeDirectory A function that returns the path to the current user’s home directory. Useful for accessing user-specific files and directories.

Syntax and Keywords

The following table summarizes the syntax and keywords related to the Foundation framework in Objective-C:

Syntax/Keyword Description
#import <Foundation/Foundation.h> A directive that imports the header file of the Foundation framework. This should be included at the beginning of any file that uses the Foundation framework.
@interface ClassName : SuperClassName <ProtocolName> A declaration that defines the interface of a class that inherits from a super class and adopts a protocol.
@end A declaration that marks the end of the interface or implementation of a class or a protocol.
@implementation ClassName A declaration that defines the implementation of a class.
@synthesize propertyName A directive that generates the getter and setter methods for a property.
@dynamic propertyName A directive that indicates that the getter and setter methods for a property are provided at runtime.
@property (attributes) type name A declaration that defines a property of a class. The attributes specify the memory management, atomicity, and access control of the property.
self A keyword that refers to the current object.
super A keyword that refers to the super class of the current object.
nil A constant that represents a null pointer.
YES A constant that represents a Boolean true value.
NO A constant that represents a Boolean false value.
NSLog(@"format", arguments) A function that prints a formatted message to the standard output or the console. The format is a string that contains placeholders for the arguments. The arguments are the values that replace the placeholders.
NSMakeRange(location, length) A function that creates and returns an NSRange structure that represents a range of values. The location is the starting point of the range. The length is the number of values in the range.
NSClassFromString(@"className") A function that returns the Class object that corresponds to a given string. The className is the name of the class.
NSSelectorFromString(@"selectorName") A function that returns the SEL object that corresponds to a given string. The selectorName is the name of the selector.
NSHomeDirectory() A function that returns the path to the current user’s home directory.

Examples

Here are some examples of the Foundation framework in Objective-C that demonstrate its usage and benefits.

Example 1: NSNumber Class

The NSNumber class is a class that represents a number of any primitive type, such as int, float, double, bool, etc. The NSNumber class allows you to store, manipulate, and compare numbers in a uniform and consistent way. The NSNumber class furthermore provides functions for converting numbers to and from different types and formats.

For example, the below code snippet illustrates how to use the NSNumber class for creating numbers, comparing them, as well as for conversion.

ObjectiveC




#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
    // Create NSNumber objects from different types of values
    NSNumber *intNumber = [NSNumber numberWithInt:42];
    NSNumber *floatNumber = [NSNumber numberWithFloat:3.14];
    NSNumber *boolNumber = [NSNumber numberWithBool:YES];
     
    // Compare NSNumber objects using the compare: method
    NSComparisonResult result = [intNumber compare:floatNumber];
    if (result == NSOrderedAscending) {
        NSLog(@"%@ is less than %@", intNumber, floatNumber);
    }
    else if (result == NSOrderedDescending) {
        NSLog(@"%@ is greater than %@", intNumber, floatNumber);
    }
    else {
        NSLog(@"%@ is equal to %@", intNumber, floatNumber);
    }
     
    // Convert NSNumber objects to different types and formats
    NSString *intString = [intNumber stringValue];
    int intVal = [intString intValue];
    float floatVal = [floatNumber floatValue];
    BOOL boolVal = [boolNumber boolValue];
     
    NSLog(@"The string value of %@ is %@", intNumber, intString);
    NSLog(@"The int value of %@ is %d", intString, intVal);
    NSLog(@"The float value of %@ is %f", floatNumber, floatVal);
    NSLog(@"The bool value of %@ is %d", boolNumber, boolVal);
 
    [pool drain];
    return 0;
}


Output:

11o

Thus, comes to light the use case of the NSNumber class in the context of storing, manipulating and comparing the numbers in the same way as a uniform and consistent manner.

Example 2: NSString Class

The NSString class is a class that is used to denote the Unicode character string. The NSString class gives methods for producing, modifying, comparison, and searching strings. The NSString class in Objective-C offers conversions to and from different encodings and formats as well.

As example, the bellow code demonstrates the usage of NSString class to construct, compare and convert strings.

ObjectiveC




#import <Foundation/Foundation.h>
 
int main(int argc, const char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
    // Create NSString objects from different sources
    NSString *string1 = @"Hello, world!";
    NSString *string2 = [NSString stringWithFormat:@"The answer is %d", 42];
    NSString *string3 = [NSString stringWithContentsOfFile:@"/Users/Desktop/test.txt"
                                                  encoding:NSUTF8StringEncoding
                                                     error:nil];
 
    // Compare NSString objects using the isEqualToString: and compare: methods
    BOOL isEqual = [string1 isEqualToString:string2];
    NSLog(@"%@ is equal to %@: %d", string1, string2, isEqual);
 
    NSComparisonResult result = [string1 compare:string2];
    if (result == NSOrderedAscending) {
        NSLog(@"%@ is less than %@", string1, string2);
    } else if (result == NSOrderedDescending) {
        NSLog(@"%@ is greater than %@", string1, string2);
    } else {
        NSLog(@"%@ is equal to %@", string1, string2);
    }
 
    // Convert NSString objects to different encodings and formats
    NSData *data = [string1 dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"The data representation of %@ is %@", string1, data);
 
    const char *utf8String = [string1 UTF8String];
    NSLog(@"The UTF-8 representation of %@ is %s", string1, utf8String);
 
    const char *cString = [string1 cStringUsingEncoding:NSASCIIStringEncoding];
    NSLog(@"The C string representation of %@ is %s", string1, cString);
 
    [pool drain];
    return 0;
}


Output:

2o

These highlight the capacity of the class NSString to develop, modify, and to match strs in an effortless way.

Example 3: NSArray Class

The class NSArray is a class that denotes an ordered collection of objects. The NSArray class offers methods of developing,processing, altering, and enumerating arrays. The NSArray class in addition to a number of methods that are used to filter and sort arrays with predicates and sort descriptors.

The code below demonstrates how to exploit the NSArray class which is applied to array creation, access and modification, as an example.

ObjectiveC




#import <Foundation/Foundation.h>
 
int main(int argc, const char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
    // Create NSArray objects from different sources
    NSArray *array1 = [NSArray arrayWithObjects:@"Apple", @"Banana", @"Cherry", nil];
    NSArray *array2 = [NSArray arrayWithObjects:@"Dog", @"Elephant", @"Fox", nil];
 
    // Access NSArray objects using the objectAtIndex:, firstObject, and lastObject methods
    NSString *firstElement = [array1 objectAtIndex:0];
    NSString *lastElement = [array2 lastObject];
    NSLog(@"The first element of %@ is %@", array1, firstElement);
    NSLog(@"The last element of %@ is %@", array2, lastElement);
 
    // Modify NSArray objects using the arrayByAddingObject:, arrayByAddingObjectsFromArray:, and subarrayWithRange: methods
    NSArray *newArray1 = [array1 arrayByAddingObject:@"Date"];
    NSArray *newArray2 = [array2 arrayByAddingObjectsFromArray:array1];
    NSLog(@"The new array after adding an object to %@ is %@", array1, newArray1);
    NSLog(@"The new array after adding objects from %@ to %@ is %@", array1, array2, newArray2);
 
    [pool drain];
    return 0;
}


Output:

3o

This shows how the NSArray class is used to create, access and modify arrays clearly and quickly.

Conclusion

The framework of Foundation in Objective-C is the basic tool which provides a library of reusable code besides the common tasks, preserving time and efforts and offering solutions of typical problems and issues of application development. It involves the array of classes, which is employed for the purpose execution of different functions like handling of the data types such as strings as well as numbers and it involves the process of dealing with the files, timers, threads and the user preferences. This framework not only makes the application work reliable, efficient and secure, but also provides great features like unified memory management, serialization, localization and networking.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads