• Home
  • Basics
  • DSA
  • MAD
  • Concept
  • Practice
  • Misc
    • Tips
    • QA’s
    • Misc
  • Course
  • Home
  • Basics
  • DSA
  • MAD
  • Concept
  • Practice
  • Misc
    • Tips
    • QA’s
    • Misc
  • Course
  • #News
  • #APPS
  • #Apple WWDC
  • #Google I/O
  • #Microsoft Ignite
  • #Let’s Talk
  • #Advertise

MyCodeTips mycodetips-newlogocopy1

  • Home
  • Basics
  • DSA
  • MAD
  • Concept
  • Practice
  • Misc
    • Tips
    • QA’s
    • Misc
  • Course
Objective-c

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 🙂

  • Click to share on Reddit (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • More
  • Click to share on Pocket (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
Written by Ranjan - August 17, 2021 - 1554 Views
Tags | CheatSheets, IOS, objective-c
AUTHOR
Ranjan

This website is basically about of what we learnt from my years of experience as a software engineer on software development specifically on mobile application development, design patterns/architectures and its changing scenarios, security, troubleshooting, tools, tips&tricks and many more.

You Might Also Like

placeholder

How to insert Placeholder in UITextView

March 24, 2020
objective-c-control-statements2

Objective-C control statements and loops !

October 21, 2021
iOS Logo

Tips to consume .net webservice in IOS applications

March 5, 2014
Next Post
Previous Post

Support us

Subscribe for updates

Join 8,278 other subscribers

Latest Posts

  • Exploring Single Point Failure
    Exploring Single Point Failures: Causes and Impacts
  • primitive-datatypes-new
    Exploring the Pros and Cons of Primitive Data Types
  • best practice clean code
    Essential Coding Standards and Best Practices for Clean Code
  • YT-Featured-Templates--lld
    What Business Problems Solves in Low Level Design (LLD)
  • SRP-SingleResopnsibility
    SRP : Single Responsibility Principle in Swift and Objective-C
whiteboard

Whiteboard(PRO)

whiteboard

Whiteboard(lite)

alphabets

Kids Alphabet

do2day

Do2Day

  • #about
  • #myapps
  • #contact
  • #privacy
  • #Advertise
  • #myQuestions

Android Database Interview IOS IOSQuestions Javascript Objective-c Programming Swift Tips&Tricks Web Wordpress

  • Exploring Single Point Failures: Causes and Impacts
  • Exploring the Pros and Cons of Primitive Data Types
  • Essential Coding Standards and Best Practices for Clean Code
MyCodeTips

©mycodetips.com

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.