RSS

Protocols in Objective C

In this post we shall have a detailed discussion on what is called as the protocols in objective c.

Protocols: Protocols are Objective C version of what is called as the interface in java or C#.  A protocol is basically a list of methods which is shared among classes the methods in the protocols do not have a body they are meant to be implemented by the developer implementing the protocol for his/her class. The objective-c language does not support multiple inheritance (a class can only derive from one superclass), but much of the same functionality can be provided by protocols because a class can conform to several different protocols.

Difference between categories and protocols: The main difference between categories and protocols in that in a protocol you get some additional methods that your class has to implement while in a category you just extend the functionality of a class with few additional method so basically a protocol says, “here are some methods I’d like you to implement.” while category says, “I’m extending the functionality of this class with these additional methods.” To be more precise I would say that a protocol specifies what method a class will implement and a category adds methods to an existing class.

How to declare a protocol and how to implement it: Given below is the syntax on how to declare a protocol and how to implement it with your class.

Protocol declaration:  Given below is the syntax to declare a protocol


In the above code the name of the protocol is ProjectRules and you can notice that there are no curly brackets; this is because variables go inside the curly brackets and protocols have no variables associated with them.Code Explanation: You use the @protocol directive to declare a protocol followed by the protocol name and in between the protocol name and @end directive you declare all the methods for the protocol that you are declaring and later you can give body to those methods inside the class in which you will be implementing this protocol.

Syntax to implement a protocol: Given below is the syntax on how you will implement a protocol in a class

Code Explanation: In the above code you can see that the ProjectRules protocol has been implemented for the ProjectManager class. You use pointy brackets to implement a protocol for a particular class in objective C and in case if you are implementing more than one protocol then in that case just use a comma to separate the name of the protocol just like you do in java or C#

In the above code you can see that the ProjectManager class implements two protocols one is the ProjectRules and ClientHandling.

In objective C, you have protocols and categories.  Pointed brackets are associated with protocols.  Curved brackets (aka parentheses) are associated with categories. So just remember, “pointy protocol, curved category.

I hope that you have understood the concept of protocols in objective c and if you have any queries related to the protocols then feel free to ask us at iphone.learning@quagnitia.com or leave your query as comments until then happy iCoding and have a great Day. You may find the PDF document for this post here.

Advertisements
 
1 Comment

Posted by on September 23, 2011 in Beginners

 

Tags: , , , ,

Objective C notes

Hello readers,

It’s very nice to hear from all of you via mails and comments and it gives me pleasure to introduce the beta version for the quagnitia objective C notes a copy of which you can download from here.

I want you to give me a feedback on this notes as it’s very important for me so that i will come to know what needs to be improved from a normal readers point of view. You can mail in your queries or comments at iphone.learning@quagnitia.com.

Happy iCoding and have a great Day.

 
Leave a comment

Posted by on September 15, 2011 in Beginners

 

Working with Files

This post covers the Objective C platform class used for basic I/O.

In this post we shall learn the following:

  • Create a new file.
  • Read from an existing file.
  • Delete a file.
  • Test for an existing file.
  • Make a copy of a file.

Managing files using NSFileManager: The NSFileManager class enables you to perform many generic file-system operations and insulates an application from the underlying file system.

In Cocoa applications, a file manager object is usually your first interaction with the file system. You use this object to locate, create, copy, and move files and directories. You also use this object to get information about files and directories, such as its size, modification date, and BSD permissions. You can also use a file manager object to change the values of many file and directory attributes.

The NSFileManager class supports both the NSURL and NSString classes as ways to specify the location of a file or directory. The use of the NSURL class is generally preferred for specifying file-system items because they can convert path information to a more efficient representation internally.

If you are moving, copying, linking, or removing files or directories, you can use a delegate in conjunction with a file manager object to manage those operations. The delegate’s role is to affirm the operation and to decide whether to proceed when errors occur.

Common NSFileManager Methods:

Method

Description

– (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error

 

Move the file or directory at the specified path to a new location.
– (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error

 

Copies the item at the specified path to a new location.
– (BOOL)fileExistsAtPath:(NSString *)path

 

Returns a Boolean value that indicates whether a file or directory exists at a specified path.
– (BOOL)isWritableFileAtPath:(NSString *)path

 

Returns a Boolean value that indicates whether the invoking object appears able to write to a specified path.
– (BOOL)isReadableFileAtPath:(NSString *)path

 

Returns a Boolean value that indicates whether the invoking object appears able to read to a specified path.
– (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2

 

Returns a Boolean value that indicates whether the file or directories in specified paths have the same conetents.

 

Creating a new File:  Given below is the snap shot of the code that will help you to create a new file along with the code explanation.

Code Explanation: The above code will create a file in the document folder with the name MyFile.txt and with the content “Welcome to Quagnitia Systems have a great Day.” The NSString class has a function called as writeToFile which accepts the location as a parameter for where you want to create the file and it returns you a boolean value so with the help of the finalResult variable I am storing the result of that method and then applying a for loop to check whether the file is create in the specified location or not.

Check for existing file: Given below is the snap shot to check whether file is present or not

 

Code Explanation:  With the help of the NSFileManager instance method named fileExistsAtPath you can check for the file existence in a particular location, in the above code I am checking for file existence in the documents folder for a file named MyFile.txt.

Read from an existing file:  Given below is the snap shot of the code to read the data from an existing file.

Code Explanation:  There is no such function in the NSFileManager to read data from the file so I came up with a very basic approach that is followed by all the developers when they want to read data from a particular file. So in the above code what I am doing is first I am checking for the file existence which I want to read and then if the file exists then I am collecting the information about the file inside the NSData variable called fileData and then with the help of the string function I am reading the data in the string format and printing the result into the console.

Delete a file: Given below is the snap shot of the code to delete a file from a particular location

Code Explanation: In the above code I am using the standard function of the NSFileManager class to remove the file from a particular location.

Create a copy of the file: Given below is the snap shot of the code for creating the copy of a file.

Code Explanation: In the above code I am creating the copy of the file named MyFile.txt with a new name MyNewFile.txt. First I am checking for the file existence in the specified location and then with the help of the instance method of the NSFileManager class i.e copyItemAtPath:toPath I am copying the files now this function returns a Boolean result indicating whether the file is copied successfully or not.

I hope that you have understood how to work with files and in case if you are having any queries then feel free to ask your queries via comments or you can mail me at iphone.learning@quagnitia.com, you can find the PDF document of this post here, until then Happy iCoding and have a great Day.

 
Leave a comment

Posted by on September 15, 2011 in Beginners

 

Categories in Objective C

In this post we shall have a look at the concept of categories.

Categories:  Sometimes while working with a particular class in a project you would have wished that if only there was some way in which you could add some methods of your own in the class which already exists in the framework.

For example say you have learned how to use NSStrings or NSArray which are the class present in the foundation framework and realize that you wish the class had implemented one or two methods which you wanted as per your applications business logic. In that case the only one thing that you would do is create a subclass of the NSArray or NSString but that is not the case with Objective C.

One Solution present for this is categories. A category is a methodology in Objective c with the help of which you can extend an existing class definition without having the access to the original source code for the class and without having to create a subclass. This means that say if I want to add a method of my own in a class that already is a member of the foundation framework then I can easily do that with the help of categories.

Let’s have a look at an example where I will be adding a function inside the NSString class which will accept a parameter of string type and that function will reverse the string passed as a parameter and will return you the reversed string, so now in my project class whenever I want to reverse a string I will just add a category once which would contain a method to reverse a string inside the NSString class and then I could use this reverse string function just like any other function of the NSString class inside my application.

Note: The category that you are adding for a particular project say A will work only for that project and not for project B, for Project B you have to again create the category.

Syntax of category: The image given below is the syntax which describes how you describe a category for a particular class which is very quite similar to a class declaration with the only difference that it lacks the curly braces.

@interface NSString (MyString)

The above line tells the compiler that you are defining a new category for the NSStirng class and the name of that category is MyString. The category name is enclosed in a pair of parentheses after the class name. The MyString category contains an instance function with the help of which you will get your reversed string.

Syntax to implement the category: Once the category is declared its time to implement the category which is very similar to the class implementation in objective c.

Once the category is defined then you can use the category, given below is the image with the help of which displays how you can use the category.

Code Explanation:  Now when there is a call to the above method it makes a call to the reverse string category method and the appropriate code is executed and you get your reversed string. This is how you work with categories in objective c.

I hope that you have understood the concept of categories in objective c in case if you are having any issues or any queries then in that case feel free to ask your queries as a comment or you can mail me at iphone.learning@quagnitia.com until then happy iCoding and have a great day, and you can get the PDF of this post here.

 
1 Comment

Posted by on September 13, 2011 in Beginners

 

Tags: , , , , ,

Memory Management

Objective C uses ‘reference counting’ as its main memory management technique (wikipedia.org/wiki/Reference_counting). Every object keeps an internal count of how many times it’s ‘needed’. The system makes sure that objects that are needed are not deleted, and when an object is not needed it is deleted. This may sound like automatic garbage collection (the way it works in Java, C#), but it is not. The main difference is that in automatic GC (Java, AS3 etc.), a separate chunk of code periodically runs in the background to see what objects are being referenced and which ones are not needed. It then deletes any unused objects automatically with no special handling required by the programmer (apart from making sure all references to objects are removed when not needed). In the reference counting method, the programmer has the responsibility of declaring when he needs the object and when he’s done with the object, and object deletion takes place immediately when the object is no longer used, i.e. reference count drops to zero (See the above wikipedia links for more on the matter).

Note: Objective C 2.0 also has an option to enable automatic garbage collection. However, garbage collection is not an option when developing for iPhone so its still important to understand reference counts, object ownership etc..

Object Ownership 

It’s important to understand the concept of object ownership. In Objective C, an object owner is someone (or piece of code) that has explicitly said “Right, I need this object, don’t delete it”. This could be the person (or code) that created the object. Or it could be another person (or code) that received the object and needs it. Thus an object can have more than one owner. The number of owners an object has is also the reference count.

Object owners have the responsibility of telling the object when they are done with it. When they do, they are no longer an owner and the object’s reference count is decreased by one. When an object has no owners left (i.e. no one needs it, reference count is zero), it is deleted.

You can still use an object without being its owner (using it temporarily), but bear in mind that the object might (and probably will) get deleted in the near future. So if you need an object long-term, you should take ownership. If you only need the object there and then (e.g. within the function that you received it, or within that event loop – more on autorelease pools later), then you don’t need to take ownership.

Messages

The main messages you can send an object (regarding memory management) are:

alloc (e.g. [NSString alloc]): This allocates an instance of the object (in this case NSString). It also sets the reference count to 1. You are the only owner of this object. You must release the object when you are done with it.

new (e.g. [NSString new]): This is basically a shorthand way of writing [[NSString alloc] init]. So same rules apply as alloc.

retain (e.g. [aString retain]): You call this when you are passed an existing object (memory has already been allocated for it elsewhere), and you want to tell the object that you need it as well. This is like saying “Ok, I need this object, don’t delete it till I’m done.”. The reference count is increased by one, and you are the new owner of this object (along with any other previous owners). You must release the object when you are done with it.

release (e.g. [aString release]): You call this when you are done using an object. You are no longer the owner of the object so the reference count is decreased by one. If reference count is now zero (i.e. no owners left), then the object is automatically deleted and the memory is freed, otherwise the object stays in memory for other owners to use. It is like saying “Right, I’m done with this object, you can delete it if no one else is using it”. If you are not the owner of an object, you should not call this. If you are the owner of an object, you must call this when you are done.

autorelease (e.g. [aString autorelease]). This means that you need the object temporarily, and does not make you an owner. It’s like saying “Ok, I need this object for now, keep it in memory while I do a few things with it, then you can delete it”. More on this later in the ‘autorelease pools’ section.

copy (e.g. [aString copy]): This creates a copy of the object (depending on how the copy message has been implemented for that object) and you become an owner of the new object.

So when dealing with Objective C pointers/objects, it’s important to remember to send the correct messages. The general rule of thumb is: If you own an object (allocate, retain or copy it), you release it. If you don’t own it (came via convenience method or someone else allocated it), you don’t release it.

Autorelease Pools

An autorelease pool is an instance of NSAutoreleasePool and defines a scope for temporary objects (objects which are to be autoreleased). Any objects which are to be autoreleased (e.g. objects you send the autorelease message to or created with convenience methods) are added to the current autorelease pool. When the autorelease pool is popped (released) all objects that were added to it are also automatically released. This is a simple way of managing automatic release for objects which are needed temporarily.

E.g. You want to create a bunch of objects for temporary calculations, and instead of keeping track of all the local variables you define and then calling release for all of them at the end of your function, you can create them all withautorelease (or convenience methods) safe in the knowledge that they are going to be released next time the autorelease pool is popped. Note: there is a downside to this which I’ll discuss in the Convenience vs Explicit section.

Autorelease pools can be nested, in which case autorelease objects are added to the latest autorelease pool to be created (the pools are stacked in a Last In First Out type stack).

Example in the Autorelease, Convenience vs Explicit section.

Owning an object means explicitly declaring that you need it (by using allocnewretain or copy).

If you own an object, you need to explicitly declare that you are done using it (by using release).

Do not release an object if you are not the owner (i.e. you used autorelease on it, or it came via a convenience method, or it was simply passed in as a parameter or return value from a function).

Only retain an object if you will be needing it in the long-term. If you only need it there and then for the function you are in, you can safely use it without owning it.

Arrays, dictionaries etc. will take ownership of objects added to them (they call retain), so you do not need to explicitly retain when adding. If you own the object before adding to a collection, and you no longer need it outside of the collection, you must release it after adding.

If you are going to be using lots of temporary objects (autoreleased / from convenience methods) you may want to think about creating your own short-term autorelease pools to avoid temporary memory peaks. If you hit the memory limits on an iPhone, the app will just quit – it doesn’t matter if the objects taking up memory are no longer needed and are waiting to be released in an autorelease pool, it’s upto you to make sure you allocate and deallocate efficiently and in a timely fashion.

For more information make sure you read the official memory management docs, lots of important details there.

developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

If you want to test for memory management the in that case you may use the tool named instruments which will provide you all the necessary details about your application memory wise. Here’s a image displaying the instrument tool in action

I hope you have understood the concept of memory management in case if you are having any queries then in that case kindly mail me at iphone.learning@quagnitia.com until then Happy iCoding and have a great day you will get the PDF of this post here.

 
2 Comments

Posted by on September 6, 2011 in Beginners

 

Tags: , , ,

Objective C Strings

In this post we shall have a look at the NSString class in objective c which is used for handling strings.

NSString class: The NSString class is used to handle immutable strings, the mutable class of NSString is NSMutableString. With the help of the NSString class you can find and compare particular strings, combine strings and convert the string into a different forms like change their case or some encoding changes. Let’s have a look at some of the examples which are given below which will help you to give a basic idea on how to use NSStirng class.

Declaring a string: In Objective c the syntax to declare a string is given below:

NSString *str = @”This is how you declare string variable”;

In the above example you can see how we declare a string variable in objective c, you can also declare a string variable like the one give below

NSString *str = [[NSString alloc]init];
str = @”This is another method to declare a string”;

Now the question in your mind would be which method to use to declare a string well the answer to this is very simple any one of the above would do but make very sure that if you are using the second approach then in that case be very sure to release the memory occupied by that string as a part of memory management (we shall discuss this later).

Determining String length: If you want to find out what’s the length of a particular string then in that case you may use the inbuilt instance method of NSString class called as length here’s an image displaying  on how to use the length function

 Code Explanation: In the above the function named getStringLength is making the use of the string function called length to return the string length.

Concatenating Strings:  Their might be scenarios where you want to append one string with another so here’s a function of NSString class to do that concatenated

Code Explanation: In the above code you can see that there are two different strings str1 and str2 each carrying different data, now if you want to append the data of str2 with str1 then in that case use the instance method of the NSString class called as the stringByAppendingString now if you run the above code it will give the output as below

 

Creating Format Strings: Using NSString class static method called as stringWithFormat you can create your own formatted string.


Code Explanation:
In the above code I have used the static function called as stringWithFormat which will return a formatted string which can be used later in the code, the function stringWithFormat is similar to the java static function called format. Given below is the output of the above function


Converting String to number: Frequently a program ends up with numeric data into string object so if you want to use that numeric data it becomes impossible to use it as it is in the string format so in such scenarios a conversion needs to be done from string to number the example for which is given below

Code Explanation: if you want to convert a string into a integer, float or double number then in that case you may use the instance method of the NSString class to do that which will help you in converting the string. Given below is the output image

 Searching a String: There are times when you would like to determine whether a particular string is present or not and if it is present then at what location so for that you may use the NSRange structure with strings

 Code Explanation: str is a string variable and in case if we want to find a particular data present inside the string then in that case you have to use the structure called NSRange and using the rangeOfString method what you could do is specify the string that you are searching for.

 

String Comparison: The NSString class has a method called isEqualToString which is used to compare one string with other.

 I hope that this post has helped you out in learning strings in objective c you can find the PDF copy of this post here, kindly let me know if you have any queries regarding strings via comments or you can mail me at iphone.learning@quagnitia.com until then Happy iCoding and have a great day.

 
2 Comments

Posted by on September 5, 2011 in Beginners

 

Tags: , ,

Creating first console app using Xcode

In this post we shall learn to how to create our first console based project using Xcode.

To launch Xcode perform the following steps

a) Go to Finder.
b) Select the MacintoshHD or what ever name is given to your drive.
c) Over their you shall see a folder called as developers.
d) Inside that folder kindly select the application group.
e) Inside the application group you can locate the Xcode icon.

Click that icon and Xcode will be launched with a small icon present inside the dashboard. In the Xcode menu select the File option and from the file submenu option select the create new project option

This shall open the screen given below:

In the above screen their are two templates one for creating mac os related application and the other is for creating the iPhone applications, but since we are very new to objective c so in that case we have to first practice objective c on console based application, so from the mac os template select applications and from their kindly select the console based application which shall open a menu in front of you asking you what the project name should be so give your project an appropriate name.

Now after giving the project name you will see that a project has been created for you will see lots of files and folders which will not make any scenes on first view. For beginning just remember that the blue file at the top is called as the xcode project file.

Right click this file where you will see a list of options from their select the add -> new file option look at the image given below for more options

After that add the objective c class into the application with a proper name make sure that this objective c class is the subclass of the NSObject class, and when you do that their will be two files that will be added into the project with the extension .h and .m (yourclassname.h and yourclassname.m)

The name of my class is Calculator so their will be two files which will be added into my file that would be Calculator.h and Calculator.m

In the above image you can see a view of the .h file where you will be declaring your methods and variables, now lets have a look at the .m file

In the above image you can see the structure of the Calculator.m file where you will be implementing all your methods declared inside the Calculator.h file, the methods will be implemented between the @implementation and @end directive.

I hope that this post has helped you out in learning how to create you first xcode project, you can download the sample project from here and if you are having any questions or queries regarding the working on Xcode then feel free to contact me at iphone.learning@quagnitia.com or mention your doubts as comments.

 
Leave a comment

Posted by on August 25, 2011 in Beginners

 

Tags: , , , ,