Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Objective-C cheat sheet
- //////////// Variable declarations ///////////
- id anObject; // pointer to an object of any type
- id anObjectMaybeNil = nil; // No object
- Rectangle* rect; // pointer to an instance of Rectangle class
- //////////// Method invocation ///////////
- [receiver message]; // calling "message" method on object referred to by variable "receiver"
- [window setWidth:100 height:200]; // call "setWidth" method and pass parameters 100 and 200
- [window setTitle:@"Window Title", "hello", 100]; // call "setTitle" with argument "Window Title" and optional args "hello" and 100
- //////////// Class definition ///////////
- // importing BaseClass interface
- #import "BaseClass.h"
- // "importing" Rectangle and Logger classes
- @class Rectangle, Logger;
- // Declaring class Window
- @interface ClassExample : BaseClass // ClassExample inherited from BaseClass
- {
- // by default, all these vars are @protected
- float width; // instance variable
- Rectangle* rectangle;
- @private // only this class can access these
- Logger* log;
- }
- + alloc; // static or "class method"
- - (void)display; // instance method, no parameters
- - (void)setWidth:(int)width height:(int)height; // instance method with 2 parameters
- - (void)setTitle:(* NSString)title, ...; // instance method with 1 argument and optional arguments
- @end
- //////////// Class implementation ///////////
- // import class that we are defining
- #import "ClassExample.h"
- @implementation ClassExample
- + alloc {
- // this will be called when instance of class is created
- }
- - (void)display {
- }
- - (void)setWidth:(int)width height:(int)height {
- if ( !rectangle ) {
- // create new instance of Rectangle and initialize it
- rectangle = [[Rectangle alloc] init];
- // access directly
- rectangle->width = width;
- rectangle->height = height;
- }
- }
- @end
- //////////// Using classes ///////////
- // Class can be interacted with as an object
- Class myWindowClass = [myWindow class];
- // Is "myObject" an instance of class "Window"?
- if ( [myObject isMemberOfClass:Window]) {
- }
- // Is "myObject" an instance of class "Window"?
- if ( [myObject isMemberOfClass:NSClassFromString(@"Window")]) {
- }
- // Is "myObject" inheriting from "Window"?
- if ( [myObject isKindOfClass:Window]) {
- }
- // make an instance of class Window
- id myWindow;
- myWindow = [Window alloc];
- //////////// Class category interface ///////////
- #import "ClassExample.h"
- @interface ClassExample (CategoryName) // example of a category called CategoryName
- // no additional instance variables are allowed
- - (int)countPixels;
- @end
- //////////// Class category implementation ///////////
- #import "ClassExample+CategoryName.h"
- @implementation ClassExample (CategoryName) // implementation of methods defined in CategoryName is separate
- // methods defined in categories need to be implemented separately from the main class implementation
- -(int)countPixels {
- if ( rectangle ) {
- return rectangle->width * rectangle->height;
- }
- return 0;
- }
- //////////// Class extensions ///////////
- #import "BaseClass.h"
- @class Point;
- // main interface
- @interface ExtensionExample : BaseClass // this is the main class in this example, inherited from BaseClass
- {
- Point* center;
- }
- - (void)setCenter:(Point*)newCenter;
- @end
- // extension interface
- @interface ExtensionExample (Setters) // this is the extension of class ExtensionExample (or "anonymous category")
- // no additional instance variables are allowed
- - (Point*)getCenter;
- @end
- // main implementation block
- @implementation ExtensionExample // ALL methods need to be implemented inside of the main "implementation block"
- - (void)setCenter:(Point*)newCenter // method defined inside main interface block
- {
- center = newCenter;
- }
- - (Point*)getCenter // method defined inside extension. Implementation MUST be inside main implementation block
- {
- return center;
- }
- @end
- //////////// PropertiesExample ///////////
- @interface PropertiesExample // example of using properties
- {
- int count;
- NSString *name;
- }
- @property int count; // letting compiler know that we need getter and setter for this variable
- @property NSString *name; // letting compiler know that we need getter and setter for this variable
- @end
- // implementation
- @implementation PropertiesExample
- @synthesize count; // compiler will automatically create getter and setter
- @dynamic name; // we will create getter and setter ourselves, below
- - (NSString *)name // getter
- {
- return name;
- }
- - (void)setName: (NSString *)newName // setter
- {
- name = newName;
- }
- @end
- // accessing properties
- PropertiesExample *example = [PropertiesExample alloc];
- // setter
- example.count = 10; // using the "dot-syntax"
- [example setCount:10]; // same thing, but calling the setter manually
- example.name = @"Name";
- // getter
- int c = example.count; // using dot-syntax
- c = [example value]; // same thing, but calling getter manually
- NSString* n = example.name;
- //////////// Property attributes ///////////
- @interface PropertyAttributeExample // example of using property attributes
- {
- int age;
- NSString* firstName;
- float bigness;
- }
- @property (readonly) int age; // variable "age" cannot be modified, only getter will be created
- // getter for this one will be different
- @property (readwrite, copy, getter=sayMyName) NSString *firstName; // variable can be changed, but setter will copy object, not just assign pointer to existing one
- @property float size; // this instance variable doesn't exist, but it's ok
- @end
- @implementation PropertyAttributeExample
- // use "bigness" to store size
- @synthesize size = bigness;
- @dynamic firstName;
- // this is similar to what compiler does when "copy" attribute is set and setter is called
- - (void)setFirstName: (NSString *)newFirstName
- {
- if ( firstName != newFirstName )
- {
- [firstName release]; // kill old string
- firstName = [newFirstName copy]; // make a copy of "newFirstName" and assign it to firstName
- }
- }
- - (NSString *)sayMyName // this is THE getter, according to the @property declaration
- {
- return firstName;
- }
- @end
- //////////// Properties and dot-syntax ///////////
- self.age = 10; // this will call "setAge" setter instead of accessing instance variable called "age"
- age = 10; // this will assign 10 to variable called "age" directly
- //////////// Key-Value coding ////////////
- @interface KeyValueCodingExample // Key-Value Coding example
- {
- int age;
- }
- @property int age;
- - (void)main;
- @end
- // implementation
- @implementation KeyValueCodingExample // Key-Value Coding example
- @synthesize age;
- - (void)main
- {
- // you can set "age" using a setter
- self.age = 10;
- // or you can set "age" using KVC notation like this
- [self setValue:10 forKey:@"age"];
- // you can retrieve "age" using a getter
- int a = self.age;
- // or you can use KVC notation again
- a = [self valueForKey:@"age"];
- }
- @end
- //////////// Declaring protocol ////////////
- @protocol ProtocolExample // declaring a protocol called ProtocolExample
- - (void)displayText: (NSString *)text; // by default, method is required
- @optional
- - (void)singAndDance; // optional method
- @required
- - (int)fetchCounter; // required method
- @end
- // example of a class that adopts protocol
- @interface UsingProtocolExample : NSObject <ProtocolExample> // adopting a protocol
- @end
- @implementation UsingProtocolExample // adopting a protocol
- // we MUST implement this one, it came from the protocol
- - (void)displayText: (NSString *)text
- {
- }
- // we MUST implement this one, it came from the protocol
- - (int)fetchCounter
- {
- }
- @end
- @protocol ProtocolExample; // we are "importing" ProtocolExample
- @protocol SubProtocolExample <ProtocolExample> // incorporating one protocol into another
- @end
- //////////// Conformity to a protocol and type checking ////////////
- if ( [object conformsToProtocol:@protocol(ProtocolExample)] ) {
- // yes, "object" implements all methods defined in ProtocolExample
- }
- id <ProtocolExample> anObjectProto; // object of any type that supports ProtocolExample protocol
- Example <ProtocolExample> *obj; // object inherited from Example AND supports ProtocolExample protocol
- //////////// Selectors ////////////
- // check whether object has method "displayText"
- if ( [object respondsTo:@selector(displayText:)] ) {
- // invoke that method
- [object performSelector:@selector(displayText:) withObject:@"Hello world!"];
- // same as
- [object displayText:@"Hello world!"];
- }
- // can also refer to selectors
- SEL request = @selector(displayText:);
- // same as
- SEL request = NSSelectorFromString(@"displayText:");
- NSString *method = NSStringFromSelector(request); // this would be equal to "displayText:"
- SEL currentMethod = _cmd; // tells us what method we are in right now
- //////////// Fast enumeration ////////////
- NSArray *array = [NSArray arrayWithObjects:@"hello", @"world", nil]; // nil here means "end of array"
- for (NSString *text in array) { // go through all strings in that array one by one
- // do something with "text"
- }
- // if you wanna write class that can be enumerated, conform to NSFastEnumeration protocol
- //////////// Exception handling ////////////
- @implementation ExceptionExample // Exception handling
- - (void)main
- {
- @try {
- // do something that might throw an exception
- NSException *ex = [NSException exceptionWithName:@"ConnectionLostException", reason:@"Network went down", userInfo:@"restart modem"];
- @throw ex;
- }
- @catch( NSException *exception ) { // will catch any exception type inherited from NSException
- NSString *name = [exception name];
- NSString *reason = [exception reason];
- }
- @finally { // will get executed regardless whether exception thrown or not
- }
- }
- @end
- //////////// Threading and synchronization ////////////
- @implementation SynchronizationExample
- - (void)synchronize
- {
- @synchronized(self) {
- // will be synchronized on the instance
- }
- @synchronized(NSStringFromSelector(_cmd)) {
- // will be synchronized on the name of the currently executing method
- }
- }
- @end
- //////////// Logging ////////////
- NSString *text = @"string variable";
- NSInteger i = 42;
- // this will print out "Logging example: string variable, 42"
- NSLog(@"Logging example: %@, %@", text, i);
- // %@ inside of the format string means "Objective-C object, printed as the string returned by 'descriptionWithLocale:' if available, or 'description' otherwise" - sort of like toString() in Java
- //////////// Variable number of arguments ////////////
- @interface VariableArgumentsExample
- - (void)printStrings:(NSString *)string, ...; // this is how you define function with var number of args
- @end
- @implementation VariableArgumentsExample
- - (void)printStrings:(NSString *)string, ...
- {
- va_list ap;
- va_start(ap, string);
- NSString* str = string;
- while( str != null ) {
- NSLog( @"Got string: %@", str );
- str = va_arg( ap, (NSString *));
- }
- va_end( ap );
- }
- @end
Add Comment
Please, Sign In to add comment