Here is the most confusing paradigm of the Java even confused by an expert programmer. It is a most common mistake which states that primitives are pass by value and objects are pass by reference. This is not totally true. Actually it is half true. Primitive types like int, double, float are indeed pass by value, hence this part is true. However, objects like Person (which I made up) are pass by value too. Pass by reference concept comes from C++ in which object can be passed to a method and method can modify/change the object as it is the original one. In java you can modify the object, but if you change the reference then you can no longer change it. Here is an famous swap example which illustrates if the language is pass by value or pass by reference. If swap can be achieved then it is pass by reference.
void swap (Point arg1, Point arg2) {
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
so in main you have something like this:
Point p1...;
Point p2...;
swap(p1,p2);
In Java it works as follow: first note that p1 (or p2) is not an object's itself. It is just a reference to a Point object (like in pointer). When we pass p1 and p2 to swap function Java creates Point objects arg1 and arg2 and copy the addresses of p1 and p2 to these arguments. Therefore it is like another reference to actual copy of the object. You can think of we have two references to Page (p1) object in this point. Same argument can be made for p2. Therefore swapping arg1 and arg2 actually just change the arg1 with arg2 and when the swap function finished they will be deallocated. Hence no effect will be visible by either p1 or p2. This actually proves Java uses pass by value not pass by reference. I hope it helps.
Thursday, March 24, 2011
Wednesday, March 16, 2011
NSString to NSURL to open a webpage in Safari
For those of you having trouble of creating NSURL with a NSString, this may be the reason. If you have a new line character at the end of your string this will not be printed if you use NSLog for debugging. Hence, you will have hard time to realize that there is something wrong. So if any in any case you may have a new line at the end of your string NSURL will add it to your URL and it will not be opened by safari. Therefore, you need to remove it.
Saturday, March 5, 2011
Memory Management in Objective-C
If you assign a new allocated instance to your iVar with . notation (setter), then be careful about the memory management. Because it may leak if you don't explicitly release the allocated instance. For example below,
self.searchResult = [[[NSMutableArray alloc] init] autorelease];
you need to release RHS, setter will retain the value and if you don't release RHS then you will get memory leak.
self.searchResult = [[[NSMutableArray alloc] init] autorelease];
you need to release RHS, setter will retain the value and if you don't release RHS then you will get memory leak.