Tuesday, January 29, 2013

Delegates in Objective C

Delegate in Objective C is used when one class objects wants to assign some of its work to another object.
Example:- in NSTableView we want cell to be drawn as per requirement. So we can delegate that adding data to cell will be done by that another delegate class object.


use of category with delegate

@interface NSObject  (NSCommonDelegateMethods)
- (void) commonMethodForallclass: (NSObject *) browser;
@end




 By putting a category on NSObject , any kind of object can be used as a delegate object. There
is no need to inherit from a specialized   class.

Adding  category on NSObject  is called creating an informal protocol.

Categories in Objective C

When you want to add something to the existing class normally we go for subclassing.In Objective we can new method to the existing class and the term called as "Category".
 Suppose in Circle class u want to add method for converting radius from float to int (let say some extra rounding off). The declaration of category as

.h file

@interface Circle (Conversion)  // existing name + new name in parenthesis 
- (int *) floattoint;
@end 


It much look like class declaration.

Here category name is Conversion. You can not add instance variable to existing classes by category.

.m file

@implementation Circle (Conversion)
- (int *) floattoint
{
//here code for conversion+ return value. You can access method of circle class with self.
@end 

In category if u have same function name as existing class then in that case category function wins and every time that will be get called.

categories are used for to split the single class into multiple file. In objective C its not possible to have single class in multiple .m files.


Example
1.Maincalss
.h file
@interface MainCategory
{
 int temp1;
 int temp2;
}
@end

,m file
@implementation MainCategory
//write if u want any function
@end


2.1st category class
h file
@interface MainCategory (Category1)
-(void) settemp1 :(int) t;
@end

,m file
@implementation MainCategory (Category1)
-(void) settemp1:(int) t
{
temp1=t;
}

@end


3.2nd category class
h file
@interface MainCategory (Category2)
-(void) settemp2 :(int) t;
@end

,m file
@implementation MainCategory (Category2)
-(void) settemp2:(int) t
{
temp2=t;
}

@end

main function
int main (int argc, const char *argv[])
{
MainCategory *maincat;
maincat = [[MainCategory alloc] init];
[maincat settemp1: 34];
[maincat settemp2: 24];
[thing release];
return (0);


Category are used for forward declaration.
You can implement method in main class without declaring it in @interface. If you want to use same method out side the class better to  write new category  and in that category @interface declare that method and implementation part of that category will not have anything.


Categories are used for adding informal protocols to an object.




Properties in Objective C

Properties is the feature of the Objective C .
It reduces lots of code writing.
Its mainly used for accessor i.e. getting and setting data member. compiler will add that code of getter and setter with respect to the thread safe or not.
syntax

.h file

#import <Foundation/Foundation.h>
@interface Circle : Shape {
int color;
int radius;
}
@property int color;
@property int radius;
@end 

.m file
#import "circle.h"
@implementation Circle
@synthesize color;
@synthesize radius;
//here code of implementation 
@end



in above example for color and radius getter and setter will be added by compiler.
@property does work of declaration of setter and getter.
@synthesize does work of creating implementation of setter and getter.

u can acces these data member with dot operator outside. 
ex
circle.radius=10; //setter method will be get called sometime these setter can be thread safe.

We saw uses of property with simple data type.
If u want to use with class objects then its better to do with some extra attributes.
ex
@property (retain) Rect *circleorigin;// retain means at the time of setting method is written by compiler       object will be retained .
same way there are some attrinute:
1.nonatomic:- when u do not want that data member should not be thread safe . faster access.
2.copy:- objects copy will be get created.
3.assign:- if u do not want to retain that object.
4.readwrite:- we can read and write values to data member (
 By default, properties are mutable).
5.readonly:- for ready only properties. generate getter. not require setter.


 Suppose u want the internal name and property name should be different.
create data member inside class declaration and use as below
@synthesize  color=circlecolor;

inside setter method circlecolor value will be get set.  This is useful normally when u are referencing that data member inside class should be accessible without self.
By default when u want to access that data member anywhere u have to access with either objectname.datamember or inside class self.datamember.




Object Creation and initialization in Objective C

COCO suggest to use alloc and init method for object creation.
alloc:- allocates the required memory for the object and initializes memory content to zero.
init :- will initializes the object data members.

alloc and init should be chaining like this
Rect *rect=[[Rect alloc] init];
should not like

Rect *rect=[Rect alloc];
[rect init];
Reason for this is init sometimes return the object which is not same as on which method get called so.
init sometime create new object sometime that object require extra space eg. in String object .


When writing your custom init method always call [super init] to initialize the super classes.
as mentioned earlier init may return the different object so always call 
self= [super init];// as subclassing will take part of it in main derived class.


There is copy method which creates  brand new object and to make the new object same as on which it is called.

Monday, January 28, 2013

Memory Management in Objective C

Objective C 2.0 introduces garbage collection  to take care of memory.


Reference Counting/Retain counting:-
Every object has an integer with it called reference count or retain count.  Which keep count of that object are in use. When you are giving object to some class/ code and used retain when giving then retain/reference count is increased by one.
Eg.
 -(NSString*)  name
{
 return [name retain];//here name reference count is increased by one
}

When that class done with that object then it calls release on it it decrement reference / retain count by one. When reference count reduces to 0 (Zero)  that objects get freed from memory (by sending dealloc message to it).  System gets that memory.

Object creation through alloc/ new/copy set this count 1.

Declaration of retain, release
- (id) retain;
- (void) release;
- (unsigned) retainCount;

Never call dealloc manually system calls it automatically when count goes to zero.

Autorelease(pool to hold objects temporarily when pool destroy release all objects)

In COCO there is autorelease pool .ie class name NSAutoreleasePool. It holds the objects(collection of objects) that automatically gets released.
NSObject supreme base class of all objective C class has
- (id) autorelease;
method. When we call autorelease on object it means the release message is sent to object in sometime future.When call to  autorelease  method particular object is get added to NSAutoreleasePool. When that pool is destroyed all the object contain in that pool gets release method.

When you are using AppKit , COCO automatically creates and destroys  an autorelease pool on a regular basis.


Important the functions like

+ (id)stringWithFormat:(NSString *)format, ...

usually return the object with autorelease called on it so we do not require to take care for free that memory.

Some objects are like singleton

NSColor *color= [NSColor blueColor];

Any Ui application is in event loop , continuous  waiting for the input. 
Cocoa creates an autorelease pool before it starts handling the event and destroys the pool after the event is handled. So in this case u have to take care of the object u kept in autorelease pool and which u require after the completion of events. eg + (id)stringWithFormat:(NSString *)format, ...
object created with this method at time of event , will live after event .

A best example of custom autorelease pool take from book  Learning Objective C on the Mac By Mark Dalrymple | Scott Knaster
in below example the pool maintain so that memory will not reach at certain level.
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
int i;
for (i = 0; i < 1000000; i++) {
id object = [someArray objectAtIndex: i];
NSString *desc = [object descrption];
// and do something with the description
if (i % 1000 == 0) {
      [pool release];
    pool = [[NSAutoreleasePool alloc] init];
    }
}
[pool release]


After every 1000 time pool is released so that memory will be available for next time to use.

 Autorelease pools are kept as a stack: if you make a new autorelease pool, it gets added to the top of the stack. An autorelease  message puts the receiver into the topmost pool. If you put an object into a pool, and then make a new pool and destroy it, the autoreleased object will still be around, because the pool holding that object is still in existence.

Garbage Collection objective C 2.0 onwards
Its same like as Java just create object use it , do not worry about its destruction . Garbage collector will find the use of object and it will automatically destroy the object. Developer has no need to worry abt it.
 Like the autorelease pool, garbage collection is triggered at the end of an event loop.

ARC VS Garbage collection

ARC is not a Garbage Collector. It is better to think of it as manual reference counting (retain/release/autorelease) calls which are added by the compiler. It also uses some runtime tricks.
OS has no method of Garbage Collection. Even so, Garbage Collection is entirely unnecessary (for all practical purposes) when ARC is used. ARC works its magic at compile time to do the reference counting for you thereby making it unnecessary (and actually non-allowed) to use any other sort of memory management.

Saturday, January 26, 2013

COCO Foundation Framework in Objective C

This framework mainly consists of classes like NSArray , NSString etc.
Some classe starts with  CF they belongs to core foundation . Core  foundation is like COCO but implemented in c. Max of its code is open source. eg CFArray.
Classes starts with NS all are part of COCO.

NSValue
It used   to allow items of such data types to be added to collections such as instances of NSArray and NSSetIt can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids. 
Creation with
+ (NSValue *)value:(const void *)value withObjCType:(const char *)type
Ex: NSValue *value= [NSValue valueWithBytes: &rect objCType: @encode(NSRect)];
to retrive u can use [value getValue: &rect];

NSNumber
Its subclass of NSValue .Mainly for converting primitive data type into objective C object.
Creation with:-

+ (NSNumber *) numberWithChar: (char) value;
+ (NSNumber *) numberWithInt: (int) value;
+ (NSNumber *) numberWithFloat: (float) value;
+ (NSNumber *) numberWithBool: (BOOL) value;

NSPonit:-

typedef struct _NSPoint {
float x;
float y;
} NSPoint;

Initialization:-

1. NSPonit point = NSMakePoint (9, 18); // this is used when initializing NSPonit when passing its Object tot any function. without specifying object 
eg.[obj getStr: NSMakePoint (9, 18)];
2. NSPonit point = { 9, 18 };

 NSSize
typedef struct _NSSize {
float width;
float height;
} NSSize;

 NSRect
typedef struct _NSRect {
NSPoint origin;
NSSize size;
} NSRect;

same way of initialization as NSPoint NSMakePoint()NSMakeSize(), and NSMakeRect()

NSRange:-
typedef struct _NSRange {
unsigned int location;
unsigned int length;
} NSRange;

Mainly used for finding range. location pointing to starting point  and length specifies the length from location. Ex. used in string.
When location has NSNotFound means range does not refer to anything.
Initialization
same way of intialization as NSPoint  normal + NSMakeRange (9, 18);

NSString:-
NSString are immutable. Once created you can not change them. You can just access it.
Its class used for storing/creating/access string.
Some of common method used for string are
1. length :- for getting length of string
2.stringWithFormat: :-for creating  string with format specifier. mainly  for equality
eg[NSString stringWithFormat:@"I will be in office at %d am", 10];
3. isEqualToString: for comparison just return true or false depend upon match.
4.compare: does case sensitive comparison.with  character-by- character comparison.
return values are NSComparisonResult.

typedef enum _NSComparisonResult {
NSOrderedAscending = -1,
NSOrderedSame,
NSOrderedDescending
} NSComparisonResult;

eg NSOrderedAscending when left- hand value is smaller than the right- hand one.
5. For case in sensitive compare use

- (NSComparisonResult) compare: (NSString *) string options: (unsigned) mask;
with mask value is NSCaseInsensitiveSearch
maks value will be NSNumericSearch] when strings are compared as number rather than characters.
6. when want to find first  substring with its location and range then use this- (NSRange) rangeOfString: (NSString *) aString;
7.- (BOOL) hasPrefix: (NSString *) aString;    for to check prefix value
- (BOOL) hasSuffix: (NSString *) aString;    for to check suffix value.

NSMutableString Its subclass of NSString
NSMutableString are mutable string.
You can manipulate string
1.add more character with    i.- (void) appendString: (NSString *) aString;
                                             ii.- (void) appendFormat: (NSString *) format, ...;
2. delete characters with i.- (void) deleteCharactersInRange: (NSRange) range;
3.creation + (id) stringWithCapacity: (unsigned) capacity;


NSArray
For storing only objective C objects. you can not store nil also.NSArray creates static arrays.
Static array means  you can not modifies its objects.

NSMutableArray
It is subclass of NSArray.  It is mutable array i.e. modifiable array of objects.
i. Add object at end - (void) addObject: (id) anObject;
ii. remove object  - (void) removeObjectAtIndex: (unsigned) index;

NSDictionary

It is used to store the key - value pair. It uses hashing mechanism so it is faster than array.

NSMutableDictionary
subclass of NSDictionary . mutable class.

NSNull 
We can not store the nil directly into NSArray or in NSDictionary.
NSNull used to store the nil value in NSArray and NSDictionary.
Mainly used to store  nothing . 
Example :- In case of keeping the employee info. Some employee may not have bike.

Fast Enumeration

It is used for to iterate through all objects of array. this is much faster.
ex
for (NSpoint *pt in array) {
NSLog (@"Value of point %@", pt);
}



NSDate

To get the date and time.


NSDate *date = [NSDate date];// date will be having current date and time.


NSData
It is used to hold buffer. It has buffer pointer plus length of buffer. 
It is mainly used to make memory management easy.
const char *string = "This is for test";

NSData *data = [NSData dataWithBytes: string length: strlen(string) + 1];



Tuesday, January 22, 2013

Useful information for Objective C developer


Use .mm   file extension,when your file has  C++ and Objective- C code together.

For import and include there is two different ways to include/import file 
i.use < > when adding system declared file(system provided file)
ii.use " " when adding local declared file.(declared by you.)

Forward declaration is used when u do not want to add(import/include) declaration in header file.
Forward declaration tell to compiler that you will get declaration of this later part. And we can add(import/include) that file in .m or .mm file. Mostly forward declaration is used in circular dependency. It means class X uses class Y and Class Y uses Class X.

Xcode shortcut are here
http://developer.apple.com/library/mac/#documentation/IDEs/Conceptual/xcode_help-command_shortcuts/MenuCommands/MenuCommands014.html#//apple_ref/doc/uid/TP40010560-CH2-SW1

http://developer.apple.com/library/mac/#documentation/IDEs/Conceptual/xcode_help-command_shortcuts/TextCmdsByType/TextCmdsByType.html#//apple_ref/doc/uid/TP40010560-CH4-SW1

http://developer.apple.com/library/mac/#documentation/IDEs/Conceptual/xcode_help-command_shortcuts/SystemAndOther/SystemAndOther.html#//apple_ref/doc/uid/TP40010560-CH5-SW3


About

Powered by Blogger.