Accepting The Complexity of Objective C

I think variable declaration is the part of any programming language that appears what will you find next during learning and development.
For example when you start to develop with Object Pascal you find soon that is a well defined, structured and organized language. Because you have to define variables just in the beginning lines of the method.

var
     myString : String;   // you have to define me just in variable  section.
begin
    myString := "This is Pascal";  // you can assign value to the variable just in the body.
    ...
end;

In Java you feel more free to define a variable. There is no specified place for defining variables.

String myString = "This is Java"; // you can define me everywhere and just assign the value.

However in Objective C you need more steps to do the same:

NSString *myString;    // A pointer to a NSString object has declared
testString = [NSString alloc];    // memory allocating
[myString init];        // initializing the variable
myString = @"This is Objective C";  // Assigning value to the variable

It looks like assembly. There are more lines in compare with other high-level languages such as Java. Without a doubt it is a pretty complicated. Hoever, you can write it in a more compact style as following:

NSString *myString;    // A pointer to a NSString object has declared
testString = [[NSString alloc] init];    // memory allocating and initializing the variable
myString = @"This is Objective C";  // Assigning value to the variable

Ok, Is that all? No there is something more to be careful about it. If you create an object using alloc or copy, you need to free that object manually. Don’t attempt to release the memory for the object that you didn’t create it.
So the code should be changed to this:

NSString *myString;    // A pointer to a NSString object has declared
testString = [[NSString alloc] init];    // memory allocating and initializing the variable
myString = @"This is Objective C";  // Assigning value to the variable
NSLog(myString); // Prints myString's content through console.
[myString release]; // Sends release messages to the object.

5 lines of code to show a short message through console is pretty much than our expectation. Ok, now let find out what I gain by paying these much lines of code. The good news is that I have more control over my objects lifecycle. I am not worry to get suspended by garbage collector. This is just a part of the payment you have to pay to develop for Mac’s products such as iPhone and iPad.
This is a comprehensive article about memory management in Objective C.

This entry was posted in Objective C, Software Engineering, Software Market Demands. Bookmark the permalink.

2 Responses to Accepting The Complexity of Objective C

  1. amir says:

    excellent article about objective programming your words alwaya inspired me and very useful and practical

Leave a Reply