Thursday, August 8, 2013

Objective C tutorial

It's a combination of object oriented programming, managed runtime and C programming language.

Methods are invoked like this
output = [object method];
output = [object methodWithInput:input];
Methods can return a value

id myObject = [NSString string];
id means anyType not known at compile time
All objective C object variables are pointer types so instead of id above we could have written NSString*

Nested messages are those where the output of one method or message call is the input to the other. It is written as
[NSString stringWithFormat:[prefs format]];

Method names can be split:
-(BOOL) writeToFile:(NSString*)path atomically:(BOOL)useAuxilaryFile;
and invoked as
BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];
writeToFile:atomically is the method name

Code inside square brackets means you are sending a message to an object or a class.

property accessors are camel-cased for set as in setCaption and no mention of get as in caption

Instead of object and method notation in the square brackets, you can use object.method;

 Objects are created by assignment and allocation
NSNumber* value = [[NSNumber alloc] initWithFloat: 1.0];
NSString* string2 = [[NSString alloc] init];
[string2 release]

Interfaces are defined as :
@interface Photo:NSObject {
            NSString* caption;
            NSString* photographer;
}

@end symbols ends the class declaration.

Dealloc method is called to free up memory

Reference counting is done on objects. You manage local references. If you create an object with alloc or copy, send it to autorelease the old object and retain the new one. You can use keywords such as autorelease, release,  retain and super dealloc.

You only need to release that which you alloc.

Logging is done with syntax like this:
NSLog( @"The current date and time is: %@", [NSDate date] );

The nil object is the functional equivalent of NULL.

Categories are one of the most useful features of Objective-C. It lets you add methods to an existing class just like C# extensions.
For eg: to add a method to NSString to determine if the contents are URL, you could specify:
@interface NSString (Utilities)
- (BOOL) isURL;
@end;
Utilities is the name of the Categories.

No comments:

Post a Comment