Friday, February 1, 2013

File operation in objective C

You can use the standard c functions.
fopen(), fread(), fwrite(), open(), read() and write().


You can write objects of NSArray, NSDictionary, etc directly into file. There is having separate method ex writetoFile: method.

Example if u wrote array of string in Array and if u wrote that array into file. File will be having stuff like this

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<string>this is test 1</string>
<string>this is test 2</string>
<string>this is test 3</string>
</array>
</plist>

Some object have serialization and deserialization method which will write directly to file.

 An NSCoder  is an abstract class that defines a bunch of useful methods for converting your objects into an NSData  and back. So this is useful in serialization and de serialization. We are using  We’ll be NSKeyedArchiver  and NSKeyedUnarchiver classes which are subclass of  NSCoder.

NSKeyedArchiver is uses key/value pairs to hold an object’s information. It uses the name of the variable as key easy for decode also.

Some useful information

nib - it is called for .xib files (nib -  NeXT Interface Builder).  After compilation of xib we get the .nib file. .xib is a xml file.

Flow when nib files are used:-
When nib file loaded in to memory all the connection related to that nib files are set mean all IBoutlet get allocated and initialized. After the connection has been set awakeFromNib is sent to every object that was created.


 When the nib file was loaded into memory when the program ran, the objects were deserialized, and new NSWindow  and NSTextField  objects were created and hooked together

Protocols in Objective C

Protocols are like interface in Java. It is having all methods. The implementation of the methods of this protocols are implemented in other class in which they are derived/subclassed.

Syntax / Protocols are declared as follows:-


@protocol NSObserver
- (void) response: (NSString *) str;
@end

When class is derived from protocol then that class must be implement all the methods of that protocol.

Deriving / adopting protocol 

@interface NSHttpRequest : NSObject < NSObserver , NSRequestSend >
{
// instance variables
}
// methods
@end 

You can specify the protocol name in the datatype like declaration or return type.
Example:-
id< NSObserver > obj;

It is telling that obj will hold anytime of object which has adopted NSObserver protocol.

There are two different types of methods in protocol.
i.Optional
ii. Required

When class derive/ adopted protocol need not compulsory to implements optional methods.
Required methods are compulsory to implement.
Method without any directive are compulsory to implement.

Ex:.

@protocol NSHttpObserver
- (void) response: (NSString *) str;// compulsory to implement
@optional 
-(NSString*) getHeader; // optional to implement

@required
- (void)setUri(NSString*) uri;// compulsory to implement
- (void)setProxy(NSString*) proxy;// compulsory to implement


@end // BaseballPlayer









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.

About

Powered by Blogger.