Cheatsheet of Objective-C

Objective-C is the primary programming language you use when writing software for OS X and iOS. It’s a superset of the C programming language and provides object-oriented capabilities and a dynamic runtime. Objective-C inherits the syntax, primitive types, and flow control statements of C and adds syntax for defining classes and methods. It also adds language-level support for object graph management and objects literals while providing dynamic typing and binding, deferring many responsibilities until runtime.

This is a quick reference and a small cheatsheet, there is a lot to discuss objective-c but in another article, we will try to cover all the aspects including below in a detailed manner.

Declaring Classes


Classes are declared using two files: a header (.h) file and an implementation (.m) file.

The header file should contain (in this order):

  • Any needed #import statements or forward @class declarations
  • Any protocol declarations
  • An @interface declaration specifying which class you’re inheriting from
  • All publicly accessible variables, properties and methods
  • The implementation file should contain (in this order):
  • Any needed #import statements
  • An anonymous category, or class extension, for any private variables or properties
  • An @implementation declaration specifying the class
  • All public and private methods

id : Known as the anonymous or dynamic object type, it can store a reference to any type of object with no need to specify a pointer symbol.

id delegate = self.delegate;

Class : Used to denote an object’s class and can be used for introspection of objects.

Class aClass = [UIView class];

Method : Used to denote a method and can be used for swizzling methods.

Method aMethod = class_getInstanceMethod(aClass, aSelector);

BOOL : Used to specify a boolean type where 0 is considered NO (false) and any non-zero value is considered YES (true). Any nil object is also considered to be NO so there is no need to perform an equality check with nil (e.g. just write if (someObject) not if (someObject != nil)).

// Boolean
BOOL isBool = YES; // Or NO

// Format: type const constantName = value;
NSString *const kRPShortDateFormat = @"MM/dd/yyyy";

// Format: #define constantName value
#define kRPShortDateFormat @"MM/dd/yyyy"


#import "AnyHeaderFile.h"
@interface ClassName : SuperClass
// define public properties
// define public methods
@end

Class Implementation (.m)

#import "YourClassName.h"

@interface ClassName ()
// define private properties
// define private methods
@end

@implementation ClassName {
// define private instance variables
}
// implement methods
@end

Defining Methods

- (type)doIt;
- (type)doItWithA:(type)a;
- (type)doItWithA:(type)a
 b:(type)b;

Implementing Methods

- (type)doItWithA:(type)a
 b:(type)b {
 // Do something with a and b...
 return retVal;
}

Creating an Object

ClassName * myObject = [[ClassName alloc] init];

Calling a Method

[myObject doIt];
[myObject doItWithA:a];
[myObject doItWithA:a b:b];

Declaring Variables

Variable types
int 
float
double
BOOL
ClassName * NSString *, NSArray *, etc.
id Can hold reference to any object

Defining Properties

@property (attribute1, attribute2)
type propertyName;
strong Adds reference to keep object alive
weak Object can disappear, become nil
assign Normal assign, no reference
copy Make copy on assign
nonatomic Make not threadsafe, increase perf
readwrite Create getter&setter (default)
readonly Create just getter

Using Properties

[myObject setPropertyName:a];
myObject.propertyName = a; // alt
a = [myObject propertyName];
a = myObject.propertyName; // alt

What is a Property?

1) Automatically defines a private instance variable:
type _propertyName;
2) Automatically creates a getter and setter:
- (type)propertyName;
- (void)setPropertyName:(type)name;
Using _propertyName uses the private instance
variable directly. Using self.propertyName uses
the getter/setter.

Custom Initializer

- (id)initWithParam:(type)param {
 if ((self = [super init])) {
_propertyName = param;
 }
 return self;
}

NSString Quick

NSString *personOne = @"my";
NSString *personTwo = @"codetips";
NSString *combinedString =
[NSString stringWithFormat:@"%@: Hello, %@!",personOne, personTwo];
NSLog(@"%@", combinedString);
NSString *tipString = @"24.99";
float tipFloat = [tipString floatValue];

NSArray Quick

NSMutableArray *array = [@[person1, person2] mutableCopy];
[array addObject:@"codetips"];
NSLog(@"%d items!", [array count]);
for (NSString *person in array) {
 NSLog(@"Person: %@", person);
}
NSString *waldo = array[2];

NSArray Access Syntax

NSArray *example = @[ @"hi", @"there", @23, @YES ];
NSLog(@"item at index 0: %@", example[0]);

NSDictionary Access Syntax

NSDictionary *example = @{ @"hi" : @"there", @"iOS" : @"people" };

Blocks

// As a local variable
returnType (^blockName)(parameterTypes) = ^returnType(parameters) {
    // Block code here
};

// As a property
@property (nonatomic, copy) returnType (^blockName)(parameterTypes);

// As a method parameter
- (void)someMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName {
    // Block code here
};

// As an argument to a method call
[someObject someMethodThatTakesABlock: ^returnType (parameters) {
    // Block code here
}];

// As a typedef
typedef returnType (^TypeName)(parameterTypes);
TypeName blockName = ^(parameters) {
    // Block code here
};
NSLog(@"hi %@", example[@"hi"]);

Commenting

// This is an inline comment

/* This is a block comment
   and it can span multiple lines. */

// You can also use it to comment out code
/*
- (SomeOtherClass *)doWork
{
    // Implement this
}
*/

Pragma to organize your code

#pragma mark - Use pragma mark to logically organize your code

// Declare some methods or variables here

#pragma mark - They also show up nicely in the properties/methods list in Xcode

// Declare some more methods or variables here

Try-Catch

@try {
    // The code to try here
}
@catch (NSException *exception) {
    // Handle the caught exception
}
@finally {
    // Execute code here that would run after both the @try and @catch blocks
}

Happy Coding 🙂


Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top