Author:GoalKicker.com
No description
Tags
Support Statistics
¥.00 ·
0times
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
Objective-C Notes for ProfessionalsObjective-C® Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial Objective-C® group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 100+ pages of professional hints and tricks
Page
2
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with Objective-C Language 2 ............................................................................ Section 1.1: Hello World 2 ................................................................................................................................................. Chapter 2: Basic Data Types 4 .................................................................................................................................. Section 2.1: SEL 4 ............................................................................................................................................................... Section 2.2: BOOL 4 .......................................................................................................................................................... Section 2.3: id 5 ................................................................................................................................................................. Section 2.4: IMP (implementation pointer) 5 ................................................................................................................. Section 2.5: NSInteger and NSUInteger 6 ...................................................................................................................... Chapter 3: Enums 8 .......................................................................................................................................................... Section 3.1: typedef enum declaration in Objective-C 8 ............................................................................................... Section 3.2: Converting C++ std::vector<Enum> to an Objective-C Array 8 ............................................................... Section 3.3: Defining an enum 9 ...................................................................................................................................... Chapter 4: Structs 10 ...................................................................................................................................................... Section 4.1: Defining a Structure and Accessing Structure Members 10 .................................................................... Section 4.2: CGPoint 10 .................................................................................................................................................... Chapter 5: Classes and Objects 12 .......................................................................................................................... Section 5.1: Dierence between allocation and initialization 12 .................................................................................. Section 5.2: Creating classes with initialization values 12 ............................................................................................ Section 5.3: Specifying Generics 13 ................................................................................................................................ Section 5.4: Singleton Class 13 ........................................................................................................................................ Section 5.5: The "instancetype" return type 14 ............................................................................................................. Chapter 6: Inheritance 15 ............................................................................................................................................. Section 6.1: Car is inherited from Vehicle 15 .................................................................................................................. Chapter 7: Methods 17 ................................................................................................................................................... Section 7.1: Class methods 17 .......................................................................................................................................... Section 7.2: Pass by value parameter passing 17 ........................................................................................................ Section 7.3: Pass by reference parameter passing 17 ................................................................................................. Section 7.4: Method parameters 18 ................................................................................................................................ Section 7.5: Create a basic method 18 ........................................................................................................................... Section 7.6: Return values 19 .......................................................................................................................................... Section 7.7: Calling methods 19 ...................................................................................................................................... Section 7.8: Instance methods 20 ................................................................................................................................... Chapter 8: Properties 21 ............................................................................................................................................... Section 8.1: Custom getters and setters 21 .................................................................................................................... Section 8.2: Properties that cause updates 22 .............................................................................................................. Section 8.3: What are properties? 23 ............................................................................................................................. Chapter 9: Random Integer 26 .................................................................................................................................. Section 9.1: Basic Random Integer 26 ............................................................................................................................ Section 9.2: Random Integer within a Range 26 ........................................................................................................... Chapter 10: BOOL / bool / Boolean / NSCFBoolean 27 ................................................................................ Section 10.1: BOOL/Boolean/bool/NSCFBoolean 27 .................................................................................................... Section 10.2: BOOL VS Boolean 27 ................................................................................................................................. Chapter 11: Continue and Break! 28 ......................................................................................................................... Section 11.1: Continue and Break Statement 28 .............................................................................................................
Page
3
Chapter 12: Key Value Coding / Key Value Observing 29 ............................................................................ Section 12.1: Most Common Real Life Key Value Coding Example 29 ........................................................................ Section 12.2: Querying KVC Data 29 .............................................................................................................................. Section 12.3: Collection Operators 30 ............................................................................................................................. Section 12.4: Key Value Observing 32 ............................................................................................................................ Chapter 13: NSString 35 ................................................................................................................................................. Section 13.1: Encoding and Decoding 35 ........................................................................................................................ Section 13.2: String Length 35 .......................................................................................................................................... Section 13.3: Comparing Strings 35 ................................................................................................................................. Section 13.4: Splitting 36 ................................................................................................................................................... Section 13.5: Searching for a Substring 37 ..................................................................................................................... Section 13.6: Creation 37 .................................................................................................................................................. Section 13.7: Changing Case 38 ....................................................................................................................................... Section 13.8: Removing Leading and Trailing Whitespace 38 ..................................................................................... Section 13.9: Joining an Array of Strings 38 .................................................................................................................. Section 13.10: Formatting 39 ............................................................................................................................................ Section 13.11: Working with C Strings 39 ......................................................................................................................... Section 13.12: Reversing a NSString Objective-C 39 ...................................................................................................... Chapter 14: NSArray 41 ................................................................................................................................................. Section 14.1: Creating Arrays 41 ...................................................................................................................................... Section 14.2: Accessing elements 41 ............................................................................................................................... Section 14.3: Using Generics 41 ....................................................................................................................................... Section 14.4: Reverse an Array 42 .................................................................................................................................. Section 14.5: Converting between Sets and Arrays 42 ................................................................................................. Section 14.6: Converting NSArray to NSMutableArray to allow modification 42 ....................................................... Section 14.7: Looping through 42 .................................................................................................................................... Section 14.8: Enumerating using blocks 43 .................................................................................................................... Section 14.9: Comparing arrays 43 ................................................................................................................................. Section 14.10: Filtering Arrays With Predicates 43 ......................................................................................................... Section 14.11: Sorting array with custom objects 44 ...................................................................................................... Section 14.12: Sorting Arrays 44 ...................................................................................................................................... Section 14.13: Filter NSArray and NSMutableArray 45 .................................................................................................. Section 14.14: Add objects to NSArray 45 ....................................................................................................................... Section 14.15: Finding out the Number of Elements in an Array 45 ............................................................................. Section 14.16: Creating NSArray instances 45 ................................................................................................................ Chapter 15: NSMutableArray 46 ................................................................................................................................ Section 15.1: Sorting Arrays 46 ......................................................................................................................................... Section 15.2: Creating an NSMutableArray 46 ............................................................................................................... Section 15.3: Adding elements 46 .................................................................................................................................... Section 15.4: Insert Elements 46 ...................................................................................................................................... Section 15.5: Deleting Elements 46 .................................................................................................................................. Section 15.6: Move object to another index 47 .............................................................................................................. Section 15.7: Filtering Array content with Predicate 47 ................................................................................................ Chapter 16: NSDictionary 48 ........................................................................................................................................ Section 16.1: Create 48 ...................................................................................................................................................... Section 16.2: Fast Enumeration 48 .................................................................................................................................. Section 16.3: Creating using literals 48 ........................................................................................................................... Section 16.4: Creating using dictionaryWithObjectsAndKeys: 48 ................................................................................ Section 16.5: NSDictionary to NSArray 49 ...................................................................................................................... Section 16.6: NSDictionary to NSData 49 .......................................................................................................................
Page
4
Section 16.7: NSDictionary to JSON 49 ........................................................................................................................... Section 16.8: Creating using plists 49 .............................................................................................................................. Section 16.9: Setting a Value in NSDictionary 49 ........................................................................................................... Section 16.10: Getting a Value from NSDictionary 50 ................................................................................................... Section 16.11: Check if NSDictionary already has a key or not 50 ............................................................................... Section 16.12: Block Based Enumeration 50 ................................................................................................................... Chapter 17: NSMutableDictionary 52 ...................................................................................................................... Section 17.1: NSMutableDictionary Example 52 ............................................................................................................. Section 17.2: Removing Entries From a Mutable Dictionary 53 ................................................................................... Chapter 18: NSDate 55 .................................................................................................................................................... Section 18.1: Convert NSDate that is composed from hour and minute (only) to a full NSDate 55 ........................ Section 18.2: Converting NSDate to NSString 55 ........................................................................................................... Section 18.3: Creating an NSDate 56 .............................................................................................................................. Section 18.4: Date Comparison 56 .................................................................................................................................. Chapter 19: NSURL 58 ..................................................................................................................................................... Section 19.1: Create 58 ...................................................................................................................................................... Section 19.2: Compare NSURL 58 ................................................................................................................................... Section 19.3: Modifying and Converting a File URL with removing and appending path 58 .................................... Chapter 20: NSUrl send a post request 60 .......................................................................................................... Section 20.1: Simple POST request 60 ............................................................................................................................ Section 20.2: Simple Post Request With Timeout 60 .................................................................................................... Chapter 21: NSData 61 .................................................................................................................................................... Section 21.1: Create 61 ...................................................................................................................................................... Section 21.2: NSData and Hexadecimal String 61 ......................................................................................................... Section 21.3: Get NSData length 62 ................................................................................................................................ Section 21.4: Encoding and decoding a string using NSData Base64 62 ................................................................... Chapter 22: NSPredicate 63 ......................................................................................................................................... Section 22.1: Filter By Name 63 ....................................................................................................................................... Section 22.2: Find movies except given ids 64 .............................................................................................................. Section 22.3: Find all the objects which is of type movie 64 ........................................................................................ Section 22.4: Find Distinct object ids of array 64 .......................................................................................................... Section 22.5: Find movies with specific ids 64 ............................................................................................................... Section 22.6: Case Insensitive comparison with exact title match 64 ......................................................................... Section 22.7: Case sensitive with exact title match 64 .................................................................................................. Section 22.8: Case Insensitive comparison with matching subset 65 ......................................................................... Chapter 23: NSRegularExpression 66 ..................................................................................................................... Section 23.1: Check whether a string matches a pattern 66 ........................................................................................ Section 23.2: Find all the numbers in a string 66 .......................................................................................................... Chapter 24: NSJSONSerialization 67 ...................................................................................................................... Section 24.1: JSON Parsing using NSJSONSerialization Objective-C 67 ..................................................................... Chapter 25: NSCalendar 69 .......................................................................................................................................... Section 25.1: System Locale Information 69 .................................................................................................................. Section 25.2: Initializing a Calendar 69 ........................................................................................................................... Section 25.3: Calendrical Calculations 69 ...................................................................................................................... Chapter 26: NSAttributedString 71 .......................................................................................................................... Section 26.1: Using Enumerating over Attributes in a String and underline part of string 71 .................................. Section 26.2: Creating a string that has custom kerning (letter spacing) editshare 71 ........................................... Section 26.3: Create a string with text struck through 71 ............................................................................................ Section 26.4: How you create a tri-color attributed string 72 .....................................................................................
Page
5
Chapter 27: NSTimer 73 ................................................................................................................................................. Section 27.1: Storing information in the Timer 73 .......................................................................................................... Section 27.2: Creating a Timer 73 ................................................................................................................................... Section 27.3: Invalidating a timer 73 ............................................................................................................................... Section 27.4: Manually firing a timer 74 ......................................................................................................................... Chapter 28: NSObject 75 ............................................................................................................................................... Section 28.1: NSObject 75 ................................................................................................................................................ Chapter 29: NSSortDescriptor 76 ............................................................................................................................. Section 29.1: Sorted by combinations of NSSortDescriptor 76 .................................................................................... Chapter 30: NSTextAttachment 77 .......................................................................................................................... Section 30.1: NSTextAttachment Example 77 ................................................................................................................ Chapter 31: NSCache 78 ................................................................................................................................................. Section 31.1: NSCache 78 .................................................................................................................................................. Chapter 32: NSUserDefaults 79 ................................................................................................................................. Section 32.1: Simple example 79 ..................................................................................................................................... Section 32.2: Clear NSUserDefaults 79 .......................................................................................................................... Chapter 33: Subscripting 80 ......................................................................................................................................... Section 33.1: Subscripts with NSArray 80 ....................................................................................................................... Section 33.2: Custom Subscripting 80 ............................................................................................................................ Section 33.3: Subscripts with NSDictionary 80 ............................................................................................................... Chapter 34: Low-level Runtime Environment 82 .............................................................................................. Section 34.1: Augmenting methods using Method Swizzling 82 .................................................................................. Section 34.2: Attach object to another existing object (association) 83 .................................................................... Section 34.3: Calling methods directly 83 ...................................................................................................................... Chapter 35: Fast Enumeration 85 ............................................................................................................................. Section 35.1: Fast enumeration of an NSArray with index 85 ...................................................................................... Section 35.2: Fast enumeration of an NSArray 85 ........................................................................................................ Chapter 36: Categories 86 ............................................................................................................................................ Section 36.1: Conforming to protocol 86 ........................................................................................................................ Section 36.2: Simple Category 86 ................................................................................................................................... Section 36.3: Declaring a class method 86 .................................................................................................................... Section 36.4: Adding a property with a category 87 .................................................................................................... Section 36.5: Create a Category on XCode 87 .............................................................................................................. Chapter 37: Protocols 91 ............................................................................................................................................... Section 37.1: Optional and required methods 91 ........................................................................................................... Section 37.2: Checking existence of optional method implementations 91 ............................................................... Section 37.3: Forward Declarations 91 ........................................................................................................................... Section 37.4: Conforming to Protocols 92 ...................................................................................................................... Section 37.5: Basic Protocol Definition 92 ...................................................................................................................... Section 37.6: Check conforms Protocol 92 .................................................................................................................... Chapter 38: Protocols and Delegates 93 .............................................................................................................. Section 38.1: Implementation of Protocols and Delegation mechanism 93 ............................................................... Chapter 39: Blocks 94 ...................................................................................................................................................... Section 39.1: Block Typedefs 94 ...................................................................................................................................... Section 39.2: Blocks as Properties 94 ............................................................................................................................. Section 39.3: Blocks as local variables 95 ...................................................................................................................... Section 39.4: Blocks as Method Parameters 95 ............................................................................................................ Section 39.5: Defining and Assigning 95 ........................................................................................................................
Page
6
Chapter 40: XML parsing 96 ........................................................................................................................................ Section 40.1: XML Parsing 96 ........................................................................................................................................... Chapter 41: Declare class method and instance method 98 ...................................................................... Section 41.1: How to declare class method and instance method 98 ......................................................................... Chapter 42: Predefined Macros 99 .......................................................................................................................... Section 42.1: Predefined Macros 99 ................................................................................................................................ Chapter 43: Grand Central Dispatch 100 .............................................................................................................. Section 43.1: What is Grand central dispatch 100 ......................................................................................................... Chapter 44: Format-Specifiers 101 ......................................................................................................................... Section 44.1: Integer Example - %i 101 ........................................................................................................................... Chapter 45: Logging 102 ............................................................................................................................................... Section 45.1: Logging 102 ................................................................................................................................................ Section 45.2: NSLog Output Format 102 ....................................................................................................................... Section 45.3: Removing Log Statements from Release Builds 102 ............................................................................ Section 45.4: Logging Variable Values 102 ................................................................................................................... Section 45.5: Empty message is not printed 103 .......................................................................................................... Section 45.6: Using __FUNCTION __ 103 ..................................................................................................................... Section 45.7: NSLog vs printf 103 ................................................................................................................................... Section 45.8: Logging NSLog meta data 104 ................................................................................................................ Section 45.9: NSLog and BOOL type 104 ....................................................................................................................... Section 45.10: Logging by Appending to a File 105 ...................................................................................................... Chapter 46: Error Handling 106 ................................................................................................................................. Section 46.1: Error & Exception handling with try catch block 106 .............................................................................. Section 46.2: Asserting 106 .............................................................................................................................................. Chapter 47: Modern Objective-C 108 ...................................................................................................................... Section 47.1: Literals 108 .................................................................................................................................................. Section 47.2: Container subscripting 108 ....................................................................................................................... Chapter 48: Singletons 110 .......................................................................................................................................... Section 48.1: Using Grand Central Dispatch (GCD) 110 ................................................................................................ Section 48.2: Creating Singleton and also preventing it from having multiple instance using alloc/init, new 110 ............................................................................................................................................................................. Section 48.3: Creating Singleton class and also preventing it from having multiple instances using alloc/init 111 ............................................................................................................................................................. Chapter 49: Multi-Threading 112 .............................................................................................................................. Section 49.1: Creating a simple thread 112 .................................................................................................................... Section 49.2: Create more complex thread 112 ............................................................................................................ Section 49.3: Thread-local storage 113 ......................................................................................................................... Chapter 50: Unit testing using Xcode 114 ............................................................................................................ Section 50.1: Note: 114 ..................................................................................................................................................... Section 50.2: Testing a block of code or some method: 114 ....................................................................................... Section 50.3: Testing asynchronous block of code: 114 .............................................................................................. Section 50.4: Measuring Performance of a block of code: 115 ................................................................................... Section 50.5: Running Test Suits: 115 ............................................................................................................................. Chapter 51: Memory Management 116 .................................................................................................................. Section 51.1: Memory management rules when using manual reference counting 116 ........................................... Section 51.2: Automatic Reference Counting 117 ......................................................................................................... Section 51.3: Strong and weak references 118 .............................................................................................................. Section 51.4: Manual Memory Management 118 ..........................................................................................................
Page
7
Credits 120 ............................................................................................................................................................................ You may also like 122 ......................................................................................................................................................
Page
8
GoalKicker.com – Objective-C® Notes for Professionals 1 About Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/ObjectiveCBook This Objective-C® Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official Objective-C® group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to web@petercv.com
Page
9
GoalKicker.com – Objective-C® Notes for Professionals 2 Chapter 1: Getting started with Objective-C Language Version Release Date 1.0 1983-01-01 2.0 2007-10-27 Modern 2014-03-10 Section 1.1: Hello World This program will output "Hello World!" #import <Foundation/Foundation.h> int main(int argc, char * argv[]) { NSLog(@"Hello World!"); } #import is a pre-processor directive, which indicates we want to import or include the information from that file into the program. In this case, the compiler will copy the contents of Foundation.h in the Foundation framework to the top of the file. The main difference between #import and #include is that #import is "smart" enough to not reprocess files that have already been included in other #includes. The C Language documentation explains the main function. The NSLog() function will print the string provided to the console, along with some debugging information. In this case, we use an Objective-C string literal: @"Hello World!". In C, you would write this as "Hello World!", however, Apple's Foundation Framework adds the NSString class which provides a lot of useful functionality, and is used by NSLog. The simplest way to create an instance of NSString is like this: @">string content here". Technically, NSLog() is part of Apple's Foundation Framework and is not actually part of the Objective-C language. However, the Foundation Framework is ubiquitous throughout Objective-C programming. Since the Foundation Framework is not open-source and cannot be used outside of Apple development, there are open-source alternatives to the framework which are associated with OPENStep and GNUStep. Compiling the program Assuming we want to compile our Hello World program, which consist of a single hello.m file, the command to compile the executable is: clang -framework Foundation hello.m -o hello Then you can run it: ./hello This will output: Hello World!
Page
10
GoalKicker.com – Objective-C® Notes for Professionals 3 The options are: -framework: Specifies a framework to use to compile the program. Since this program uses Foundation, we include the Foundation framework. -o: This option indicate to which file we'd like to output our program. In our case hello. If not specified, the default value is a.out.
Page
11
GoalKicker.com – Objective-C® Notes for Professionals 4 Chapter 2: Basic Data Types Section 2.1: SEL Selectors are used as method identifiers in Objective-C. In the example below, there are two selectors. new and setName: Person* customer = [Person new]; [customer setName:@"John Doe"]; Each pair of brackets corresponds to a message send. On the first line we send a message containing the new selector to the Person class and on the second line we send a message containing the setName: selector and a string. The receiver of these messages uses the selector to look up the correct action to perform. Most of the time, message passing using the bracket syntax is sufficient, but occasionally you need to work with the selector itself. In these cases, the SEL type can be used to hold a reference to the selector. If the selector is available at compile time, you can use @selector() to get a reference to it. SEL s = @selector(setName:); And if you need to find the selector at runtime, use NSSelectorFromString. SEL s NSSelectorFromString(@"setName:"); When using NSSelectorFromString, make sure to wrap the selector name in a NSString. It is commonly used to check if a delegate implements an optional method. if ([self.myDelegate respondsToSelector:@selector(doSomething)]) { [self.myDelegate doSomething]; } Section 2.2: BOOL The BOOL type is used for boolean values in Objective-C. It has two values, YES, and NO, in contrast to the more common "true" and "false". Its behavior is straightforward and identical to the C language's. BOOL areEqual = (1 == 1); // areEqual is YES BOOL areNotEqual = !areEqual // areNotEqual is NO NSCAssert(areEqual, "Mathematics is a lie"); // Assertion passes BOOL shouldFlatterReader = YES; if (shouldFlatterReader) { NSLog(@"Only the very smartest programmers read this kind of material."); } A BOOL is a primitive, and so it cannot be stored directly in a Foundation collection. It must be wrapped in an NSNumber. Clang provides special syntax for this: NSNumber * yes = @YES; // Equivalent to [NSNumber numberWithBool:YES]
Page
12
GoalKicker.com – Objective-C® Notes for Professionals 5 NSNumber * no = @NO; // Equivalent to [NSNumber numberWithBool:NO] The BOOL implementation is directly based on C's, in that it is a typedef of the C99 standard type bool. The YES and NO values are defined to __objc_yes and __objc_no, respectively. These special values are compiler builtins introduced by Clang, which are translated to (BOOL)1 and (BOOL)0. If they are not available, YES and NO are defined directly as the cast-integer form. The definitions are found in the Objective-C runtime header objc.h Section 2.3: id id is the generic object pointer, an Objective-C type representing "any object". An instance of any Objective-C class can be stored in an id variable. An id and any other class type can be assigned back and forth without casting: id anonymousSurname = @"Doe"; NSString * surname = anonymousSurname; id anonymousFullName = [NSString stringWithFormat:@"%@, John", surname]; This becomes relevant when retrieving objects from a collection. The return types of methods like objectAtIndex: are id for exactly this reason. DataRecord * record = [records objectAtIndex:anIndex]; It also means that a method or function parameter typed as id can accept any object. When an object is typed as id, any known message can be passed to it: method dispatch does not depend on the compile-time type. NSString * extinctBirdMaybe = [anonymousSurname stringByAppendingString:anonymousSurname]; A message that the object does not actually respond to will still cause an exception at runtime, of course. NSDate * nope = [anonymousSurname addTimeInterval:10]; // Raises "Does not respond to selector" exception Guarding against exception. NSDate * nope; if([anonymousSurname isKindOfClass:[NSDate class]]){ nope = [anonymousSurname addTimeInterval:10]; } The id type is defined in objc.h typedef struct objc_object { Class isa; } *id; Section 2.4: IMP (implementation pointer) IMP is a C type referring to the implementation of a method, also known as an implementation pointer. It is a pointer to the start of a method implementation. Syntax:
Page
13
GoalKicker.com – Objective-C® Notes for Professionals 6 id (*IMP)(id, SEL, …) IMP is defined by: typedef id (*IMP)(id self,SEL _cmd,…); To access this IMP, the message “methodForSelector” can be used. Example 1: IMP ImpDoSomething = [myObject methodForSelector:@selector(doSomething)]; The method addressed by the IMP can be called by dereferencing the IMP. ImpDoSomething(myObject, @selector(doSomething)); So these calls are equal: myImpDoSomething(myObject, @selector(doSomething)); [myObject doSomething] [myObject performSelector:mySelector] [myObject performSelector:@selector(doSomething)] [myObject performSelector:NSSelectorFromString(@"doSomething")]; Example 2: SEL otherWaySelector = NSSelectorFromString(@“methodWithFirst:andSecond:andThird:"); IMP methodImplementation = [self methodForSelector:otherWaySelector]; result = methodImplementation( self, betterWaySelector, first, second, third ); NSLog(@"methodForSelector : %@", result); Here, we call [NSObject methodForSelector which returns us a pointer to the C function that actually implements the method, which we can the subsequently call directly. Section 2.5: NSInteger and NSUInteger The NSInteger is just a typedef for either an int or a long depending on the architecture. The same goes for a NSUInteger which is a typedef for the unsigned variants. If you check the NSInteger you will see the following: #if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 typedef long NSInteger; typedef unsigned long NSUInteger; #else typedef int NSInteger; typedef unsigned int NSUInteger; #endif The difference between an signed and an unsigned int or long is that a signed int or long can contain negative
Page
14
GoalKicker.com – Objective-C® Notes for Professionals 7 values. The range of the int is -2 147 483 648 to 2 147 483 647 while the unsigned int has a range of 0 to 4 294 967 295. The value is doubled because the first bit isn't used anymore to say the value is negative or not. For a long and NSInteger on 64-bit architectures, the range is much wider. Most methods Apple provides are returning an NS(U)Integer over the normal int. You'll get a warning if you try to cast it to a normal int because you will lose precision if you are running on a 64-bit architecture. Not that it would matter in most cases, but it is easier to use NS(U)Integer. For example, the count method on an array will return an NSUInteger. NSNumber *iAmNumber = @0; NSInteger iAmSigned = [iAmNumber integerValue]; NSUInteger iAmUnsigned = [iAmNumber unsignedIntegerValue]; NSLog(@"%ld", iAmSigned); // The way to print a NSInteger. NSLog(@"%lu", iAmUnsigned); // The way to print a NSUInteger. Just like a BOOL, the NS(U)Integer is a primitive datatype, so you sometimes need to wrap it in a NSNumber you can use the @ before the integer to cast it like above and retrieve it using the methods below. But to cast it to NSNumber, you could also use the following methods: [NSNumber numberWithInteger:0]; [NSNumber numberWithUnsignedInteger:0];
Page
15
GoalKicker.com – Objective-C® Notes for Professionals 8 Chapter 3: Enums Section 3.1: typedef enum declaration in Objective-C A enum declares a set of ordered values - the typedef just adds a handy name to this. The 1st element is 0 etc. typedef enum { Monday=1, Tuesday, Wednesday } WORKDAYS; WORKDAYS today = Monday;//value 1 Section 3.2: Converting C++ std::vector<Enum> to an Objective-C Array Many C++ libraries use enums and return/receive data using vectors that contain enums. As C enums are not Objective-C objects, Objective-C collections cannot be used directly with C enums. The example below deals with this by using a combination of an NSArray and generics and a wrapper object for the array. This way, the collection can be explicit about the data type and there is no worry about possible memory leaks with C arrays Objective-C objects are used. Here is the C enum & Objective-C equivalent object: typedef enum { Error0 = 0, Error1 = 1, Error2 = 2 } MyError; @interface ErrorEnumObj : NSObject @property (nonatomic) int intValue; + (instancetype) objWithEnum:(MyError) myError; - (MyError) getEnumValue; @end @implementation ErrorEnumObj + (instancetype) objWithEnum:(MyError) error { ErrorEnumObj * obj = [ErrorEnumObj new]; obj.intValue = (int)error; return obj; } - (MyError) getEnumValue { return (MyError)self.intValue; } @end
Page
16
GoalKicker.com – Objective-C® Notes for Professionals 9 And here is a possible use of it in Objective-C++ (the resulting NSArray can be used in Objective-C only files as no C++ is used). class ListenerImpl : public Listener { public: ListenerImpl(Listener* listener) : _listener(listener) {} void onError(std::vector<MyError> errors) override { NSMutableArray<ErrorEnumObj *> * array = [NSMutableArray<ErrorEnumObj *> new]; for (auto&& myError : errors) { [array addObject:[ErrorEnumObj objWithEnum:myError]]; } [_listener onError:array]; } private: __weak Listener* _listener; } If this kind of solution is to be used on multiple enums, the creation of the EnumObj (declaration & implementation) can be done using a macro (to create a template like solution). Section 3.3: Defining an enum Enums are defined by the following the syntax above. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA, MyEnumValueB, MyEnumValueC, }; You also can set your own raw-values to the enumeration types. typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB = 5, MyEnumValueC = 10, }; You can also specify on the first value and all the following will use it with increment: typedef NS_ENUM(NSUInteger, MyEnum) { MyEnumValueA = 0, MyEnumValueB, MyEnumValueC, }; Variables of this enum can be created by MyEnum enumVar = MyEnumValueA.
Page
17
GoalKicker.com – Objective-C® Notes for Professionals 10 Chapter 4: Structs Section 4.1: Defining a Structure and Accessing Structure Members The format of the struct statement is this: struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables]; Example: declare the ThreeFloats structure: typedef struct { float x, y, z; } ThreeFloats; @interface MyClass - (void)setThreeFloats:(ThreeFloats)threeFloats; - (ThreeFloats)threeFloats; @end Sending an instance of MyClass the message valueForKey: with the parameter @"threeFloats" will invoke the MyClass method threeFloats and return the result wrapped in an NSValue. Section 4.2: CGPoint One really good example of a struct is CGPoint; it's a simple value that represents a 2-dimensional point. It has 2 properties, x and y, and can be written as typedef struct { CGFloat x; CGFloat y; } CGPoint; If you used Objective-C for Mac or iOS app development before, you've almost certainly come across CGPoint; CGPoints hold the position of pretty much everything on screen, from views and controls to objects in a game to changes in a gradient. This means that CGPoints are used a lot. This is even more true with really performance- heavy games; these games tend to have a lot of objects, and all of these objects need positions. These positions are often either CGPoints, or some other type of struct that conveys a point (such as a 3-dimensional point for 3d games). Points like CGPoint could easily be represented as objects, like @interface CGPoint { CGFloat x; CGFloat y; } ... //Point-related methods (e.g. add, isEqualToPoint, etc.)
Page
18
GoalKicker.com – Objective-C® Notes for Professionals 11 @property(nonatomic, assign)CGFloat x; @property(nonatomic, assign)CGFloat y; @end @implementation CGPoint @synthesize x, y; ... @end However, if CGPoint was used in this way it would take a lot longer to create and manipulate points. In smaller, faster programs this wouldn't really cause a difference, and in those cases it would be OK or maybe even better to use object points. But in large programs where points are be used a lot, using objects as points can really hurt performance, making the program slower, and also waste memory, which could force the program to crash.
Page
19
GoalKicker.com – Objective-C® Notes for Professionals 12 Chapter 5: Classes and Objects Section 5.1: Dierence between allocation and initialization In most object oriented languages, allocating memory for an object and initializing it is an atomic operation: // Both allocates memory and calls the constructor MyClass object = new MyClass(); In Objective-C, these are separate operations. The class methods alloc (and its historic sibling allocWithZone:) makes the Objective-C runtime reserve the required memory and clears it. Except for a few internal values, all properties and variables are set to 0/NO/nil. The object then is already "valid" but we always want to call a method to actually set up the object, which we call an initializer. These serve the same purpose as constructors in other languages. By convention, these methods start with init. From a language point of view, they are just normal methods. // Allocate memory and set all properties and variables to 0/NO/nil. MyClass *object = [MyClass alloc]; // Initialize the object. object = [object init]; // Shorthand: object = [[MyClass alloc] init]; Section 5.2: Creating classes with initialization values #import <Foundation/Foundation.h> @interface Car:NSObject { NSString *CarMotorCode; NSString *CarChassisCode; } - (instancetype)initWithMotorValue:(NSString *) motorCode andChassisValue:(NSInteger)chassisCode; - (void) startCar; - (void) stopCar; @end @implementation Car - (instancetype)initWithMotorValue:(NSString *) motorCode andChassisValue:(NSInteger)chassisCode{ CarMotorCode = motorCode; CarChassisCode = chassisCode; return self; } - (void) startCar {...} - (void) stopCar {...} @end The method initWithMotorValue: type andChassisValue: type will be used to initialize the Car objects.
Page
20
GoalKicker.com – Objective-C® Notes for Professionals 13 Section 5.3: Specifying Generics You can enhance your own classes with generics just like NSArray or NSDictionary. @interface MyClass<__covariant T> @property (nonnull, nonatomic, strong, readonly) NSArray<T>* allObjects; - (void) addObject:(nonnull T)obj; @end Section 5.4: Singleton Class What is a Singleton Class? A singleton class returns the same instance no matter how many times an application requests it. Unlike a regular class, A singleton object provides a global point of access to the resources of its class. When to Use Singleton Classes? Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource. How to Create Singleton Classes First, create a New file and subclass it from NSObject. Name it anything, we will use CommonClass here. Xcode will now generate CommonClass.h and CommonClass.m files for you. In your CommonClass.h file: #import <Foundation/Foundation.h> @interface CommonClass : NSObject { } + (CommonClass *)sharedObject; @property NSString *commonString; @end In your CommonClass.m File: #import "CommonClass.h" @implementation CommonClass + (CommonClass *)sharedObject { static CommonClass *sharedClass = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedClass = [[self alloc] init]; }); return sharedClass; } - (id)init { if (self = [super init]) { self.commonString = @"this is string"; }
Comments 0
Loading comments...
Reply to Comment
Edit Comment