{"id":13428159,"url":"https://github.com/Avocarrot/ios-cheatsheet","last_synced_at":"2025-03-16T01:31:51.144Z","repository":{"id":16588899,"uuid":"19343229","full_name":"Avocarrot/ios-cheatsheet","owner":"Avocarrot","description":"A quick reference cheat sheet for iOS developers. ","archived":false,"fork":false,"pushed_at":"2018-03-05T16:52:44.000Z","size":18,"stargazers_count":294,"open_issues_count":3,"forks_count":44,"subscribers_count":36,"default_branch":"master","last_synced_at":"2025-02-05T05:34:40.498Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Avocarrot.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-05-01T11:56:20.000Z","updated_at":"2025-01-21T20:00:53.000Z","dependencies_parsed_at":"2022-09-24T08:23:21.087Z","dependency_job_id":null,"html_url":"https://github.com/Avocarrot/ios-cheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Avocarrot%2Fios-cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Avocarrot%2Fios-cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Avocarrot%2Fios-cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Avocarrot%2Fios-cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Avocarrot","download_url":"https://codeload.github.com/Avocarrot/ios-cheatsheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243814900,"owners_count":20352037,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T01:00:47.888Z","updated_at":"2025-03-16T01:31:50.876Z","avatar_url":"https://github.com/Avocarrot.png","language":null,"funding_links":[],"categories":["Platforms","Uncategorized"],"sub_categories":["Uncategorized"],"readme":"iOS Cheatsheet\n==============\n\nA quick reference cheat sheet for iOS developers so that you turn coffee into code much faster:)\n\n**Note**: The [Avocarrot](http://www.avocarrot.com/?utm_source=github\u0026utm_medium=ios-cheatsheet) team will do its best to keep this cheatsheet updated but feel free to send your pull requests if you want to add a new entry or edit something.\n\n##Contents\n\n###Objective-C Basics\n\n- [Classes](#classes)\n- [Methods](#methods)\n- [Operators](#operators)\n- [Properties](#properties)\n- [Constants](#constants)\n- [Flow control statements](#flow-control-statements)\n- [Delegates](#delegates)\n- [Blocks](#blocks)\n\n###Foundation Framework Classes\n\n- [NSString](#nsstring)\n- [NSArray](#nsarray)\n- [NSDictionary](#nsdictionary)\n- [Objective-C Literals](#objective-c-literals)\n\n###C Related Code\n\n- [Enumerated Types](#enumerated-types)\n\n\n##Objective-C Basics\n\n###Classes\n\n####Class header\n\n```objc\n@interface Human : NSObject\n\n// Define properties and methods\n\n@end\n```\n\n####Class implementation\n\n```objc\n#import \"Human.h\"\n\n@interface Human ()\n// Define private properties and methods\n@end\n\n@implementation Human {\n// Define private instance variables\n}\n\n// Provide method implementation code\n\n@end\n```\n\n####Creating an instance\n\n```objc\nHuman * anObject = [[Human alloc] init];\n```\n\n\n###Methods\n\n####Defining methods\n\n```objc\n// Returns nothing and has no arguments\n- (void)foo;\n\n// Returns an NSString object and takes one argument of type NSObject\n- (NSString *)fooWithArgument:(NSObject *)bar;\n\n// Takes two arguments one of type NSObject and a second one of type NSString\n- (void)fooWithArgument:(NSObject *)bar andArgument:(NSString *)baz;\n\n// Defines a class method (note the + sign)\n+ (void)aClassMethod;\n```\n\n####Implementing methods\n\n```objc\n- (NSString *)fooWithArgument:(NSObject *)bar{\n    // Do something here\n    return retValue;\n}\n```\n\n####Calling a method\n\n```objc\n[anObject someMethod];\n[anObject someMethodWithArg1:arg1 andArg2:arg2];\n```\n\n\n### Operators\n\n#### Arithmetic Operators\n\nOperator | Description\n:---: | :---:\n+ | Addition\n- | Subtraction\n* | Multiplication\n/ | Division\n% | Modulo\n\n#### Comparison Operators\n\nOperator | Description\n:---: | :---:\nx == y |    Returns true if x is equal to y\nx \u003e y | Returns true if x is greater than y\nx \u003e= y |    Returns true if x is greater than or equal to y\nx \u003c y | Returns true if x is less than y\nx \u003c= y |    Returns true if x is less than or equal to y\nx != y |    Returns true if x is not equal to y\n\n\n#### Logical Operators\n\nOperator | Description\n:---: | :---:\n! | NOT\n\u0026\u0026 | Logical AND\n\u0026#124;\u0026#124; | Logical OR\n\n#### Compound Assignment Operators\n\nOperator | Description\n:---: | :---:\nx += y |    Add x to y and place result in x\nx -= y |    Subtract y from x and place result in x\nx *= y |    Multiply x by y and place result in x\nx /= y |    Divide x by y and place result in x\nx %= y |    Perform Modulo on x and y and place result in x\nx \u0026= y |    Assign to x the result of logical AND operation on x and y\nx |= y |    Assign to x the result of logical OR operation on x and y\nx ^= y |    Assign to x the result of logical Exclusive OR on x and y\n\n#### Bitwise Operators\n\nOperator | Description\n:---: | :---:\n\u0026 | Bitwise AND\n\u0026#124; | Bitwise Inclusive OR\n^ | Exclusive OR\n~ | Bit inversion\n\u003c\u003c | Shift Left\n\u003e\u003e | Shift Right\n\n#### Other operators\n\nOperator | Description\n:---: | :---:\n() | Cast\n? : | Ternary\n\u0026 | Memory Address\n* | Pointer\n\n\n###Properties\n\n####Define properties\n\n```objc\n@property (attribute1, attribute2) NSString *aProperty;\n```\n\nAttribute Type | Purpose\n:---: | ---\nstrong (iOS 4 = retain) (default)  | Creates an owning relationship to the object that is assigned to the property\nweak  (iOS 4 = unsafe_unretained) | Creates a non-owning relationship\nassign (default) | Normal assign, doesn’t perform any kind of memory-management\ncopy | Make an immutable copy of the object upon assignment\natomic (default) | Only allows one thread to access the property, which makes it threadsafe\nnonatomic |  Allows multiple threads to access the property simultaneously, which makes it not threadsafe\nreadwrite (default) | Generates both getter and setter\nreadonly | Generates only getter\ngetter=method | Use this to specify a different name for the property's getter method\nsetter=method | Use this to specify a different name for the property's setter method\n\n####Access Properties\n\n```objc\n[anObject aProperty];\n\n// Alternative\nanObject.aProperty\n```\n\n\n###Constants\n\n####Preprocessing Macros\n\nThis is not an actual constant because it defines a macro which replaces all occurrences of ```MAX_NUMBER_OF_ITEMS``` with the actual value before compile time.\n\n```objc\n#define MAX_NUMBER_OF_ITEMS 10\n```\n\n####Using const\n\nA better approach is to use ```const```.\n```objc\nNSString *const kMyName = @\"Clark\";\n```\n\n####Static and extern\n\nIf you know that the constant will only be available within it's implementation file, then you can use ```static```. Using ```static``` means that the constant will only be available in that file.\n\n```objc\nstatic NSString * const kMyName = @\"Clark\";\n```\n\nIf you want to have a constant global then you should use extern.\n\n```objc\n// .h file\nextern NSString * const kMyName;\n```\n\n```objc\n// .m file\nNSString * const kMyName = @\"Clark\";\n```\n\n###Flow control statements\n\n####If-else statement\n\n```objc\nif (someCondition) {\n    // Execute if the condition is true\n} else if (someOtherCondition) {\n    // Execute if the other condition is true\n} else {\n    // Execute if the none of the above conditions are true\n}\n```\n\n####Ternary operator\n\n```objc\nsomeCondition ? @\"True\" : @\"False\";\n```\n\n####For Loops\n\n```objc\nfor (int i = 0; i \u003c totalCount; i++) {\n    // Do something here\n}\n```\n\n####While Loop\n\n```objc\nwhile (someCondition) {\n   // Do something here\n}\n```\n\n####Do While Loop\n\n```objc\ndo {\n    // Do something here\n} while (someCondition);\n```\n\n####Switch\n\n```objc\nswitch (aLabel)\n{\n    case kLabelA:\n        // Execute this if matched\n        break;\n\n     case kLabelB:\n        // Execute this if matched\n        break;\n\n     default:\n        // Execute this if matched\n        break;\n}\n```\n\n\n###Delegates\n\nDelegates are a design pattern. A delegate allows one object to send messages to another object when an event happens. Check out [Apple docs](https:// developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html):\n\n####Become the delegate of a framework class\n\n**Step 1**\n\nDeclare that your class adopts the protocol in the class definition in the angled brackets after the class/superclass name.\n\n```objc\n// MyTableViewController.h\n\n@interface MyTableViewController : UIViewController \u003cUITableViewDelegate, UITableViewDataSource\u003e\n\n@end\n```\n\n**Step 2**\n\nSet your object as the delegate.\n\n```objc\n// MyTableViewController.m\n\n[tableView setDelegate:self];\n\n@end\n```\n\n**Step 3**\n\nImplement the delegate methods.\n\n\n####Implement your own delegate for a custom class\n\n**Step 1**\n\nDeclare the protocol methods\n\n```objc\n// Superman.h\n#import \u003cFoundation/Foundation.h\u003e\n\n@protocol SupermanDelegate \u003cNSObject\u003e\n\n- (void)dodgeBullet;\n- (void)seeThroughThings;\n- (void)fly;\n\n@optional\n- (void)eat;\n\n@end\n\n@interface Superman : NSObject\n\n// Create a property for the delegate reference\n@property (nonatomic, weak) id \u003cSupermanDelegate\u003e delegate;\n\n// Define other methods and properties\n\n@end\n\n```\n\n**Step 2**\n\nSet the delegate object\n\n```objc\n// Superman.m\n\n[self setDelegate:anObject];\n```\n\n**Step 3**\n\nStart sending delegate messages\n\n```objc\n// Superman.m\n\n[self.delegate fly];\n```\n\nFor the delegate methods that are optional, it is wise to check if the delegate can respond to that method before firing.\n\n```objc\nif ([self.delegate respondsToSelector:@selector(eat)]) {\n  [self.delegate eat];\n}\n```\n\n### Blocks\n\n\u003e Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values.\n\nFor more information see [Programming with Objective-C - Working with Blocks](https:// developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html)\n\n\n**To declare a block local variable:**\n\n```\nreturnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};\n```\n\n**To declare a block property:**\n\n```\n@property (nonatomic, copy) returnType (^blockName)(parameterTypes);\n```\n\n**To accept a block as a method parameter:**\n\n```\n- (void)aMethodThatTakesABlock:(returnType (^)(parameterTypes))blockName;\n```\n\n**To pass a block as an argument in a method call:**\n\n```\n[someObject someMethodThatTakesABlock: ^returnType (parameters) {...}];\n```\n\n**To define a block type:**\n\n```objc\ntypedef returnType (^TypeName)(parameterTypes);\nTypeName blockName = ^returnType(parameters) {...};\n```\n\n##Class Specific\n\n###NSString\n\n####Quick examples\n\n```objc\nNSString *firstName = @\"Clark\";\nNSString *lastName = @\"Kent\";\nNSString *fullName = [NSString stringWithFormat:  @\"My full name is %@ %@\",  firstName, lastName];\n```\n\n####NSString format specifier\n\nSpecifier | Description\n:---: | ---\n%@  | Objective-C object\n%zd | NSInteger\n%lx, (long) | CFIndex\n%tu | NSUInteger\n%i  | int\n%u  | unsigned int\n%hi  | short\n%hu  | unsigned short\n%%  | Literal %\n\n\n###NSArray\n\n####Quick examples\n\n```objc\n// Create an array\nNSMutableArray *anArray = [@[@\"Clark Kent\", @\"Lois Lane\"] mutableCopy];\n\n// Add new items\n[anArray addObject:@\"Lex Luthor\"];\n\n// Find array length\nNSLog(@\"Array has %d items\", [anArray count]);\n\n// Iterate over array items\nfor (NSString *person in anArray) {\n NSLog(@\"Person: %@\", person);\n}\n\n// Access item with index\nNSString *superman = anArray[0];\n\n// Remove Object @\"Clark Kent\"\n[anArray removeObject:@\"Clark Kent\"];\n\n// Remove the first Object\n[anArray removeObjectAtIndex:0];\n```\n\n###NSDictionary\n\n####Quick examples\n\n```objc\n// Create a dictionary\nNSMutableDictionary *person = [@{\n                             @\"firstname\" : @\"Clark\",\n                             @\"lastname\" : @\"Kent\",\n                             @\"age\" : [NSNumber numberWithInt:35]\n                             } mutableCopy];\n\n// Access values\nNSLog(@\"Superman's first name is %@\", person[@\"firstname\"]);\n// or\nNSLog(@\"Superman's first name is %@\", [person objectForKey:@\"firstname\"]);\n\n// Find number of items in dictionary\n[person count];\n\n// Add an object to a dictionary\n[person setObject:@\"job\" forKey:@\"teacher\"];\n\n// Remove an object to a dictionary\n[person removeObjectForKey:@\"firstname\"];\n```\n\n##Objective-C Literals\n\n**Available from LLVM Compiler version 4.0 made available with Xcode 4.4**\n\n###Strings\n```objc\nNSString *string = @\"This is a string.\";\n```\n\n###Numbers\n```objc\nNSNumber *number = @126;      // int          : Equal to [NSNumber numberWithInt:126];\nNSNumber *number = @126u;     // unsigned int : Equal to [NSNumber numberWithUnsignedInt:126u];\nNSNumber *number = @126l;     // long         : Equal to [NSNumber numberWithLong:126l];\nNSNumber *number = @126.544f; // float        : Equal to [NSNumber numberWithFloat:126.544f]\nNSNumber *number = @126.544;  // double       : Equal to [NSNumber numberWithDouble:126.544]\nNSNumber *number = @YES;      // bool         : Equal to [NSNumber numberWithBool:YES]\n```\n\n###Containers\n```objc\nNSArray *array = @[object1,object2,object3]; // Creating NSArray\nObject *object2 = array[1]; // Accessing NSArray\nmutableArray[1] = newObject; // Adding to NSMutableArray\n\nNSDictionary *dictionary = @{ @\"key1\" : object1, @\"key2\" : object2, @\"key3\" : object3 }; // Creating NSDictionary\nObject *object2 = dictionary[@\"key2\"]; // Accessing NSDictionary\nmutableDictionary[@\"name\"] = @\"Henry\"; // Adding to NSMutableDictionary\n```\n\n##C References\n\n###Enumerated Types\n\n####Apple's Examples\n\nEach enumerate is given a corresponding integer value, so\n\n```objc\ntypedef NS_ENUM(NSInteger, UIButtonType) {\n   UIButtonTypeCustom,\n   UIButtonTypeSystem,\n   UIButtonTypeDetailDisclosure,\n   UIButtonTypeInfoLight,\n   UIButtonTypeInfoDark,\n   UIButtonTypeContactAdd,\n   UIButtonTypeRoundedRect\n};\n```\n\nis the same as\n\n```objc\ntypedef NS_ENUM(NSInteger, UIButtonType) {\n   UIButtonTypeCustom = 0,\n   UIButtonTypeSystem = 1,\n   UIButtonTypeDetailDisclosure = 2,\n   UIButtonTypeInfoLight = 3,\n   UIButtonTypeInfoDark = 4,\n   UIButtonTypeContactAdd = 5,\n   UIButtonTypeRoundedRect = 6\n};\n```\n\nExplicitly defining the first enumerate's value is not required and it will default to 0.\n\n####Using an enumerated type\n\n```objc\nUIButton *button = [UIButton buttonWithType:UIButtonTypeInfoLight];\n```\n\nOr create a variable to pass into the methods like so...\n\n```objc\nUIButtonType myButtonType = UIButtonTypeCustom;\nUIButton *myButton = [UIButton buttonWithType:myButtonType];\n```\n\nBecause they are not objects, you must print enumerated types as integers\n\n```objc\nUIButtonType myButtonType = UIButtonTypeRoundedRect;\n\n// Bad, will give you a warning and might even crash\nNSLog(@\"%@\", myButtonType);\n\n// Good, will properly print the value as an integer\nNSLog(@\"%d\", myButtonType);\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAvocarrot%2Fios-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAvocarrot%2Fios-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAvocarrot%2Fios-cheatsheet/lists"}