Cocoa Quick Guide

Cocoa Tips & Tricks and Code Snippets

Created By: Debasis Das

Defining String Constants in a Cocoa Project

//The KSConstants.h file
#import <Foundation/Foundation.h>
extern NSString* const CONSTANT_ONE;
extern NSString* const CONSTANT_TWO;
@interface KSConstants : NSObject

//The KSConstants.m file
#import "KSConstants.h"
NSString* const CONSTANT_ONE = @"Value of Constant One";
NSString* const CONSTANT_TWO    = @"Value of Constant Two";

@implementation KSConstants

Creating a NSArray

Different Ways of Creating a NSArray

NSArray *array = @[@1, @2, @3];

NSArray *arrayOne = @[@"1000",@"1001",@"1002",@"1003"];

NSArray *arrayTwo = [NSArray arrayWithObjects:@"1001",@"1002",@"1003",@"1004", nil];
NSArray *arrayThree = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:@"Debasis",@"firstName",@"Das",@"lastName", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"John",@"firstName",@"Doe",@"lastName", nil]
, nil];

NSString *strings[3];
strings[0] = @"First";
strings[1] = @"Second";
strings[2] = @"Third";
NSArray *stringsArray = [NSArray arrayWithObjects:strings count:3];
// NSArray *newStringsArray =[NSArray arrayWithObjects:strings count:4]; //Will Crash, Out of bounds
NSArray *mArray = [NSArray arrayWithObjects:@"1001",@"1002",@"1003",@"1004",@"1005",@"1006", nil];// an array with at least six elements...;
id *objects; 
NSRange range = NSMakeRange(2, 4);
objects = (__bridge NSArray *)(malloc(sizeof(id) * range.length));
[mArray getObjects:objects range:range];
for (int i = 0; i < range.length; i++) {
NSLog(@"objects: %@", objects[i]);

Creating a NSDictionary

Different Ways of Creating a NSDictionary

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Object One",@"keyOne",@"Object Two",@"keyTwo", nil];

NSMutableDictionary *mutDict = [[NSMutableDictionary alloc] init];
[mutDict setValue:@"Object One" forKey:@"keyOne"];
[mutDict setValue:@"Object Two" forKey:@"keyTwo"];

NSDictionary *dictTwo = [NSDictionary dictionaryWithDictionary:mutDict];

NSDictionary *dictThree = [[NSDictionary alloc] initWithObjectsAndKeys:@"Object One",@"keyOne",@"Object Two",@"keyTwo", nil];

NSDictionary *dictFour = @{@"firstName":@"Debasis",@"lastName":@"Das"};

Array of Dictionaries

    NSArray *data = @[

Reading a File in Cocoa, Objective C

NSMutableString *mutString = [[NSMutableString alloc] initWithString:[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"WebTemplate" ofType:@"html"] encoding:NSASCIIStringEncoding error:nil]];

Reading a PLIST from Cocoa, Objective C and creating a dictionary

     NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ScreenA" ofType:@"plist"]];

Writing a String to a file in Cocoa, Objective C

NSString * tempString = @"Hello World!!";
NSError *anError = nil;
NSString *filePath =@"Users/johndoe/Desktop/file.txt";
[tempString writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:@anError];

Opening a URL from a Cocoa App in Objective C

//For opening a local HTML file in the web browser from a Cocoa Application
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"file:///Users/johndoe/Desktop/test.html"]];

//For opening an external URL from a Cocoa Application
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@""]];

Reading a JSON from a Cocoa Application

    NSError *anError = nil;
    NSData * jSonData =   [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://localhost:8080/JSONSample/SampleData.json"]];
//The json file in this case should a JSON Array
    NSArray *array =  [[NSArray alloc] initWithArray:[NSJSONSerialization JSONObjectWithData:jSonData options:NSJSONReadingMutableContainers error:&anError]];

Download to Excel in Cocoa, Objective C

    NSDate *dt1 = [NSDate date]; //This is required if you want to see how much time it requires to download to excel
    NSString *fileName = [NSString stringWithFormat:@"YourFileName%@.xls",[NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle]];
    NSSavePanel *aSavePanel = [NSSavePanel savePanel];
    [aSavePanel setAccessoryView:nil];
    [aSavePanel setNameFieldStringValue:fileName];
    int runResult = (int)[aSavePanel runModal];
    if (runResult == NSOKButton)
    NSMutableString *dataString = [[[NSMutableString alloc] init] autorelease];
    NSArray *keyArray = @[@"_id",@"firstName",@"lastName",@"age",@"email"];
    for (NSString *str in keyArray)
        [dataString appendFormat:@"%@t",str];
    [dataString appendString:@"r"];
    for (NSDictionary *dict in self.dataArray)
        for (NSString *keyStr in keyArray)
            [dataString appendFormat:@"%@t",[objedictt objectForKey:keyStr]];
        [dataString appendString:@"r"];
       [dataString writeToURL:[aSavePanel URL] atomically:YES encoding:NSUTF16StringEncoding error:nil];
    NSDate *dt2 = [NSDate date];
    double timeTaken = [dt2 timeIntervalSinceDate:dt1] * 1000;
    [self displaySuccessMessage:[NSString stringWithFormat:@"Data Downloaded Successfully. Time taken to download %d records was %f milliseconds",self.dataArray.count,timeTaken]];
//You have to implement the displaySuccessMessage method or you can simply comment the same

Opening a Panel and loading, Reading a file

	NSOpenPanel *aPanel = [NSOpenPanel openPanel];
	[aPanel setMessage:@"Choose the photo library"];
	[aPanel setPrompt:@"Load"];
	[aPanel setNameFieldLabel:@"Location"];
	[aPanel setTitle:@"Load Photo Library"];
	[aPanel setAllowsMultipleSelection:NO];
	[aPanel setCanChooseDirectories:YES];
        [aPanel setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Desktop", NSHomeDirectory()]]];
//for pointing the panel to a default location

    [aPanel beginWithCompletionHandler:^(NSInteger result){
        if (result == NSFileHandlingPanelOKButton)
                // Handles the upload or file reading here
            @catch (NSException * e)
            //If the user cancels

Generating MD5 Hash for a File, in Cocoa, Objective C

#import <CommonCrypto/CommonDigest.h > 

- (NSString *) generateMD5Hash:(NSString *)filePath {
    unsigned char dataOutput[CC_MD5_DIGEST_LENGTH];
    NSData *fileData = [[NSData alloc] initWithContentsOfFile:filePath];
    CC_MD5([fileData bytes], [fileData length], dataOutput);
    [fileData release];

    NSMutableString *md5HashStr = [[NSMutableString alloc] init];
    for (NSUInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [md5HashStr appendFormat:@"%02x", dataOutput[i]];
    return [md5HashStr autorelease];

Recursively Look for file types in a directory, Return an array of all file names

-(NSMutableArray*)searchfiles:(NSString*)basePath ofTypes:(NSArray*)fileTypes
   //basePath is the directory Path
   //fileTypes is the input array of file type extensions //@[@"jpg",@"jpeg",@"png",@"tif"];
    NSMutableArray *files = [[[NSMutableArray alloc] init] autorelease];
    NSFileManager *defFM = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *dirPath = [defFM contentsOfDirectoryAtPath:basePath error:&error];
    for(NSString *path in dirPath){
        BOOL isDir;
        path = [basePath stringByAppendingPathComponent:path];
        if([defFM fileExistsAtPath:path isDirectory:&isDir] && isDir){
            [files addObjectsFromArray:[self searchfiles:path ofTypes:fileTypes]];
    NSArray *mediaFiles = [dirPath pathsMatchingExtensions:fileTypes];
    for(NSString *fileName in mediaFiles){
        fileName = [basePath stringByAppendingPathComponent:fileName];
        [files addObject:fileName];
    return files;

This page will be continuously updated. Revisit to keep learning

Leave a Reply

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