This document provides an introduction to Objective-C, beginning with an overview of what Objective-C is and the prerequisites for learning it. It then demonstrates a simple "Hello World" program to get started. The rest of the document outlines key Objective-C concepts like objects, methods, inheritance, properties, protocols, categories and class extensions. It also discusses the Foundation framework and common Objective-C data types like NSString, NSNumber, NSArray and NSDictionary. The document uses examples to illustrate how to define and use Objective-C objects.
12. Objects
• Interface
• like Java’s Interface, but every object has one
• placed in the header file
• Implementation
• must fill minimum requirements of Interface
• placed in the implementation file
Saturday, March 9, 13
13. Example Object
// //
// MyObject.m // MyObject.h
// Implementation // Interface
#import “MyObject.h” #import <Foundation/Foundation.h>
@implementation MyObject @interface MyObject : NSObject {
int _myInt;
// method implementations go here }
@end // method declarations go here
@end
Saturday, March 9, 13
14. Objects (More Info)
• Objects have Instance Variables (ivars)
• No Class variables, use C static globals
• No enforced “public” and “private”
• Object Instances can be of type:
•id
•Class *
Saturday, March 9, 13
15. Object Methods
• Class Method or Instance Method
• Variables are “named” in the method’s
signature (fancy word for method name)
• Default return and variable type is id
Saturday, March 9, 13
16. Format of a Method
+/- (return type)methodName;
+/- (return type)methodWithVar:(var type)var;
+/- (return type)methodWithVar1:(var type)var1
! ! ! ! ! ! ! ! var2:(var type)var2;
Saturday, March 9, 13
18. Object Method Calling
• Not like C, C++, or Java
• Based on Smalltalk message passing
• The Square Brackets [] are your friend!
[object method];
[object methodWithVar:value];
[object methodWithVar1:val1
! ! ! ! ! ! ! ! var2:val2];
Saturday, March 9, 13
19. Testing Responsiveness
to a Selector
• The name of a method is its Selector
SEL mySelector = selector(myMethodWithParameter:)
• Every object inherits respondsToSelector:
• Takes the selector to test for
• Returns YES when the object can respond to
that method
• Returns NO when the object cannot respond to
that method
Saturday, March 9, 13
20. Object Constructor
• Not a special method (unlike Java)
• Just an instance method to set up the
Object’s Instance Variables
• Generally named init
Saturday, March 9, 13
23. Inheritance
• Single Inheritance from Objects
• Method Overloading Supported
• Superclass defined in the Interface
• Super class referenced with super
Saturday, March 9, 13
25. Properties
• Syntactic sugar for variable, accessor, and
mutator declarations all-in-one
• Properties are declared in the Interface and
synthesized in the Implementation
• Let you use “dot syntax” with getters and
setters
! myObjectInstance.myInt = 5;
! int x = myObjectInstance.myInt;
Saturday, March 9, 13
27. More on Properties
• Attributes
strong weak copy assign readonly
atomic nonatomic
•
@synthesize vs @dynamic
!synthesize variable = nameOfIvar;
@
• Default ivar name for variable is
_variable
• Custom getters and setters
getter = myGetter, setter = mySetter:
Saturday, March 9, 13
28. Protocols
• Like an Objective-C Interface
• Similar to Java Interfaces
• Can implement multiple Protocols
• Protocols can ‘inherit’ other Protocols
Saturday, March 9, 13
30. Categories
• The ability to add new methods to an
Object
• Changes apply to all instances of the object
• Overwrites any methods that already exist
in the class
• Cannot add Properties and ivars
• Can be dangerous
Saturday, March 9, 13
32. Class Extension
• Like Categories, but with the ability to add
ivars and Properties
• Implementations of methods required in
the main Implementation block
• Can be used to declare “private” methods
Saturday, March 9, 13
33. Class Extension
Example
//
// MyObject.m
// Class Extension
@interface MyObject ()
@property (assign) int myPrivateInt;
@end
// Implementation
@implementation MyObject
@synthesize myPrivateInt = _myPrivateInt;
// more implementation here
@end
Saturday, March 9, 13
34. Ok.
Now, lets take a look at MyObject
Saturday, March 9, 13
38. Using MyObject
• alloc class method
• use of init and
initWithInt: methods MyObject *obj = [[MyObject alloc] init];
obj.myInt = 5;
•
NSLog(@"%in", obj.myInt);
splitting up the alloc and
init method calls
MyObject *other = [MyObject alloc];
other = [other initWithInt:5];
• use of dot syntax and [other setMyInt:10];
NSLog(@"%in", [obj myInt]);
generated methods
• NSLog() for printing
messages to the console
Saturday, March 9, 13
39. One More Thing
Imports and Forward Declarations
Saturday, March 9, 13
40. Imports
• Objective-C introduces the #import
Preprocessor Directive
#import "MyHeaderFile.h"
#import <SystemHeader.h>
• Guarantees the file is only included once
• Better Practice than C’s #include
Saturday, March 9, 13
41. Forward Declarations
• A Promise to the Compiler that a Class or
Protocol will exist at Compile Time
@class PromisedObject;
@protocol PromisedProtocol;
• Minimizes the amount of #includes
Saturday, March 9, 13
42. Objective-C Data
What you get with the Foundation Framework
Saturday, March 9, 13
43. nil
• Represents the absence of an object
• Messages passed to nil return nil
• nil is for objects, NULL is for C pointers
Saturday, March 9, 13
44. YES and NO
• Boolean type BOOL for “true” and “false”
• Use BOOL with YES and NO
• Dont use _Bool or bool with true and
false from stdbool.h
Saturday, March 9, 13
45. NSNumber
• Object Representation for Integers,
Booleans, Floats, Doubles, Characters, etc.
• Object Literal Syntax
@1 @1.0 @YES @NO @(1+2) @'a'
Saturday, March 9, 13
49. Implementing
Array Subscripting
• Accessing Objects
objectAtIndexedSubscript:
• Setting Objects
setObject:atIndexedSubscript:
• The index subscript must be an integral
Saturday, March 9, 13
50. Implementing
Dictionary Subscripting
• Accessing Object values with key Objects
objectForKeyedSubscript:
• Setting Object values with key Objects
setObject:forKeyedSubscript:
Saturday, March 9, 13
51. Forin Loops
• Loop over the contents of a collection
• Foundation NSDictionary
NSArray
Framework collections
• Any implementation of the
NSFastEnumeration Protocol
• Any Subclass of NSEnumerator
Saturday, March 9, 13
52. Forin Loops Example
NSArray *array = @[@1, @2, @3, @4, @5];
for (NSNumber *num in array) {
NSLog(@"%@", num);
}
for (id num in [array reverseObjectEnumerator]) {
NSLog(@"%@", num);
}
Saturday, March 9, 13
53. Objective-C Blocks
• Functions you can declare within functions
• Can close-over variables for later use
• Can pass block functions around like data
Saturday, March 9, 13
54. Block Syntax
• Similar to C Function Pointer Syntax
return_type (^name)(parameter types) =
! ^(parameter list) {
! ! // do stuff
! };
return_type (^name)() = ^{
! ! // do stuff
! ! // takes no parameters
! };
Saturday, March 9, 13
55. Block Example
int multiplier = 5; The block itself has read
int (^mult)(int) = ^(int num){
return num * multiplier; access to variables defined
}; in the lexical scope at the
int num = mult(5); // num = 25 creation of the block.
__block int number = 0; The block can close over
void (^increment)() = ^{
number++; outside variables and
}; modify their values by
increment(); // number = 1 declaring the variable with
increment(); // number = 2 the __block modifier.
Saturday, March 9, 13
56. Type-Safe Enums
• Enums that you can declare the type they enumerate over
• int, char, unsigned char, NSUInteger, ...
• Syntax similar to Object Subclassing
typedef enum MyEnum : NSUInteger {
A, B, C
} MyEnum;
enum MyUnsignedCharEnum : unsigned char {
FIRST, SECOND, THIRD
};
typedef enum MyUnsignedCharEnum MyUnsignedCharEnum;
typedef enum : NSUInteger {
ONE, TWO, THREE
} AnotherEnum;
Saturday, March 9, 13
57. Automatic Reference
Counting
What it is, and what it means to you
Saturday, March 9, 13
58. Referencing Counting
• Nearly-Manual Memory Management
• Objects have a counter showing how many
references are using them
• Retain Objects when you receive them
[object retain];
• Release Objects when you’re done using them
[object release];
• Objects deallocate themselves when their retain
count reaches 0
Saturday, March 9, 13
59. Automatic Reference
Counting (ARC)
• Almost Compile Time Garbage Collection
• Retain and Release messages are added at compile
time by the compiler
• ARC manages when to do this for you
• strong variables are Retained when assigned
• weak variables are not Retained on assignment
and are zeroed out when deallocated
Saturday, March 9, 13
60. Retain Cycle
• Two Objects Reference Each Other
• Their retain counts can never reach 0
• Set one of the references to weak to
prevent one of the objects from retaining
the other and causing a cycle
Saturday, March 9, 13
61. So there you have it
Objective-C thrown at you
Saturday, March 9, 13
62. Useful References
• Programming with Objective-C
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/
ProgrammingWithObjectiveC/Introduction/Introduction.html
http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/
ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf
• Objective-C Cheat Sheet and Quick Reference
http://cdn5.raywenderlich.com/downloads/RW-Objective-C-Cheatsheet-v1_2.pdf
• Coding Guidelines for Cocoa
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/
CodingGuidelines.html
http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/
CodingGuidelines.pdf
• Ry’s Objective-C Tutorial
http://rypress.com/tutorials/objective-c/index.html
Saturday, March 9, 13