Cocoa, Objective C Code Snippets

Cocoa, Objective C Code Snippets

Created By: Debasis Das (22-Aug-2015)

In this post we will post loads of Cocoa, Objective C code snippets , This post will be frequently updated. Come back to learn more

NSArray & NSMutableArray Code Snippets

Creating NSArray of Numbers – Literal Syntax

NSArray *numberArray = @[@1, @2, @3];
NSLog(@"numberArray %@",numberArray);

Creating NSArray of Numbers – Convenience Constructors

      NSArray *numberWithIntArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:100],
      [NSNumber numberWithInt:200],
      [NSNumber numberWithInt:300],
      [NSNumber numberWithInt:400],nil];
      NSLog(@"numberWithIntArray %@",numberWithIntArray);

Creating NSArray of NSString – Literal Syntax

      NSArray *stringArray1 = @[@"John Doe",@"Jane Doe",@"Mary Jane",@"Debasis Das"];
      NSLog(@"stringArray1 %@",stringArray1);

 

Creating a NSArray of NSString using Convenience Constructors

      NSArray *stringArray2 = [NSArray arrayWithObjects:@"John Doe",@"Jane Doe",@"Mary Jane",@"Debasis Das", nil];
      NSLog(@"stringArray2 %@",stringArray2);

Creating a NSArray of NSDictionary using Literal Syntax

      NSArray *arrayOfDictionary = @[@{@"firstName":@"Debasis", @"lastName":@"Das"},
            @{@"firstName":@"Jane", @"lastName":@"Doe"},
            @{@"firstName":@"John", @"lastName":@"Doe"}];
      NSLog(@"arrayOfDictionary %@",arrayOfDictionary);

Creating a NSArray of NSDictionary using Convenience Constructors

      NSArray *arrayOfDictionary1 = [NSArray arrayWithObjects:
              [NSDictionary dictionaryWithObjectsAndKeys:@"Debasis",@"firstName",@"Das",@"lastName", nil],
              [NSDictionary dictionaryWithObjectsAndKeys:@"John",@"firstName",@"Doe",@"lastName", nil]
              , nil];
      NSLog(@"arrayOfDictionary1 %@",arrayOfDictionary1);

Creating an NSArray from JSON

    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]];

NSDictionary Code Snippets

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

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

NSString, NSMutableString Code Snippets

NSMutableString from Reading a File in Cocoa, Objective C

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

Writing a NSString object 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];

NSWorkspace Code Snippets

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:@"http://www.knowstack.com"]];

NSSavePanel, NSOpenPanel Code Snippets

Download to Excel in Cocoa, Objective C

    
-(IBAction)downloadToExcel:(id)sender
{
    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)
        {
            @try
            {
                // Handles the upload or file reading here
            }
            @catch (NSException * e)
            {
            }
        }
        else
        {
            //If the user cancels
        }
    }];

NSFileManager Code Snippets

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;
}

Other Code Snippets

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];
}
Posted in Cocoa, Objective C Tagged with: ,

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news