at first it loads viewDidLoad
- (void)viewWillAppear:(BOOL)animated;
// Called when the view is about to made visible. Default does nothing
- (void)viewDidAppear:(BOOL)animated;
// Called when the view has been fully transitioned onto the screen. Default does nothing
- (void)viewWillDisappear:(BOOL)animated;
// Called when the view is dismissed, covered or otherwise hidden. Default does nothing
- (void)viewDidDisappear:(BOOL)animated;
// Called after the view was dismissed, covered or otherwise hidden. Default does nothing
if you implement by the line NSLog(@"see what is that %s ", __func__); you will see the first 3 is coming one by one.
Search This Blog
Thursday, August 20, 2015
What is the difference between NIB and XIB Interface Builder file formats?
- xib = xml interface builder, nib = next interface builder
- When you compile your project, .xib file will get compiled into nib.
- Functionally nothing but the xib is a source control friendly format
- A Xib is more or less an XML document, it is the uncompiled read/write version of a nib. Once you compile a xib it becomes a nib.
- XIB is actually XML file. NIB is binary.
- XIB: Text-based XML. NIB: Archives, created by Xcode.
As of Interface Builder version 3, a new file format (with extension .xib) has been added, which is functionally identical to .nib, except it is stored in a flat file, making it more suitable for storage in revision control systems and processing by tools such as diff.
XIBs are flat files rather than being a bundle. This makes it easier
for SCM systems to deal with. When you compile your app, the XIB is
compiled into a NIB file for inclusion in your app.
The compiled NIB that is included in the app bundle is no longer editable in Interface Builder and is much smaller than the equivalent XIB or legacy NIB file.
From wikipedia:
Interface Builder is a software development application for Apple's Mac OS X operating system. It is part of Xcode (formerly Project Builder), the Apple Developer Connection developer's toolset. Interface Builder allows Cocoa and Carbon developers to create interfaces for applications using a graphical user interface. The resulting interface is stored as a .nib file, short for NeXT Interface Builder, or more recently, as a .xib file.
Interface Builder is descended from the NeXTSTEP development software of the same name. A version of Interface Builder is also used in the development of OpenStep software, and a very similar tool called Gorm exists for GNUstep. On March 27, 2008, a specialized iPhone version of Interface Builder allowing interface construction for iPhone applications was released with the iPhone SDK Beta 2.
Interface Builder was intentionally developed as a separate application, to allow interaction designers to design interfaces without having to use a code-oriented IDE, but as of Xcode 4, Apple has integrated its functionality directly into Xcode.
Interface Builder saves an application's interface as a bundle that contains the interface objects and relationships used in the application. These objects are archived (a process also known as serialization or marshalling in other contexts) into either an XML file or a NeXT-style property list file with a .nib extension. Upon running an application, the proper NIB objects are unarchived, connected into the binary of their owning application, and awakened. Unlike almost all other GUI designer systems which generate code to construct the UI (notable exceptions being Glade, Embarcadero Technologies's Delphi and C++ Builder, which stream UI objects similarly), NIBs are often referred to as freeze dried because they contain the archived objects themselves, ready to run. As of Interface Builder version 3, a new file format (with extension .xib) has been added, which is functionally identical to .nib, except it is stored in a flat file, making it more suitable for storage in revision control systems and processing by tools such as diff.
The compiled NIB that is included in the app bundle is no longer editable in Interface Builder and is much smaller than the equivalent XIB or legacy NIB file.
From wikipedia:
Interface Builder is a software development application for Apple's Mac OS X operating system. It is part of Xcode (formerly Project Builder), the Apple Developer Connection developer's toolset. Interface Builder allows Cocoa and Carbon developers to create interfaces for applications using a graphical user interface. The resulting interface is stored as a .nib file, short for NeXT Interface Builder, or more recently, as a .xib file.
Interface Builder is descended from the NeXTSTEP development software of the same name. A version of Interface Builder is also used in the development of OpenStep software, and a very similar tool called Gorm exists for GNUstep. On March 27, 2008, a specialized iPhone version of Interface Builder allowing interface construction for iPhone applications was released with the iPhone SDK Beta 2.
Interface Builder was intentionally developed as a separate application, to allow interaction designers to design interfaces without having to use a code-oriented IDE, but as of Xcode 4, Apple has integrated its functionality directly into Xcode.
Interface Builder saves an application's interface as a bundle that contains the interface objects and relationships used in the application. These objects are archived (a process also known as serialization or marshalling in other contexts) into either an XML file or a NeXT-style property list file with a .nib extension. Upon running an application, the proper NIB objects are unarchived, connected into the binary of their owning application, and awakened. Unlike almost all other GUI designer systems which generate code to construct the UI (notable exceptions being Glade, Embarcadero Technologies's Delphi and C++ Builder, which stream UI objects similarly), NIBs are often referred to as freeze dried because they contain the archived objects themselves, ready to run. As of Interface Builder version 3, a new file format (with extension .xib) has been added, which is functionally identical to .nib, except it is stored in a flat file, making it more suitable for storage in revision control systems and processing by tools such as diff.
Ref: https://en.wikipedia.org/wiki/Interface_Builder#Design
More discussion: [Ref: http://www.speirs.org/blog/2007/12/5/what-are-xib-files.html]
The Xcode tools in Leopard introduced a new file format for user interfaces. In the brach of the prehistory of Mac OS X that includes NeXT, interfaces were defined in files known as NIBs, from their .nib extension.
A NIB file is a Mac OS X package containing, usually, a keyedobjects.nib file and a classes.nib file. When building an application, these files are copied into the app's bundle and are loaded at runtime to provide the user interface for the application. For what comes next, bear in mind that the NIB in your Xcode project is the same NIB that is loaded at runtime in the application.
Interface Builder 3 on Leopard introduces a new file format: XIB. The developer experience of editing XIB files in Interface Builder is identical to editing a NIB file but, in many other ways a XIB is radically different from a NIB file. If I had one criticism of WWDC '07, it was that they didn't spend enough time explaining XIBs and their implications.
File Format
Firstly, the XIB file format is completely different from that of a NIB. A XIB is not a package - it is a single self-contained XML file. The XML schema is specific to XIBs - it is not a simple XML Property List.
This brings a couple of advantages. Firstly, it's a benefit for users of tools that are not package-aware. In early days, Interface Builder would blow away the .svn directory inside the NIB package. That hasn't been a problem for years, but other tools may still have issues.
Secondly, the file format is vaguely human-understandable. It is very dense and not entirely obvious, but one can make some sense of it. This helps in some of those last-ditch situations where you're grepping the file to find out where a particular binding is referenced.
It is worth pointing out two things that this text-based file format does not immediately deliver: hand-editability and mergability. The XIB file is an XML representation of an object graph and, as such, it is considered dangerous to edit it by hand. Merging is just a machine-assisted form of hand editing and is likely problematic. However, the text format might assist in understanding where the conflicts lie.
Working with XIBs
The primary tool for editing XIB files is, of course, Interface Builder. For many years, there has been a command line tool for manipulating nibs called nibtool. In Leopard, nibtool has been renamed (or replaced - I'm not sure) by ibtool and has acquired many new tricks.
The man page for ibtool contains a lot of detail, but it's worth noting a couple of new capabilities: the --convert option will rename old classes to new. Presumably it is ibtool --convert that allows Xcode 3.0's refactoring tools to reach into interface files.
There are also many options in ibtool for printing the details of a NIB or XIB to an XML Property List, including --objects, --connections, --hierarchy and --classes, although a mode to conveniently list the bindings in an interface sadly isn't available.
Deploying XIBs
The crucial difference between XIB and NIB for deployment is that a XIB is not a deployable file. Xcode 3 will compile a XIB into a deployable NIB when the project is built and will include that deployable NIB in the finished application.
If you're using XIB in your Xcode projects, you might see a CompileXIB build operation going past. What's actually happening there is that Xcode is calling:
ibtool --errors --warnings --notices --output-format human-readable-text --compile your.xib output.nib
It's ibtool that compiles XIB to NIB, not Xcode itself, and it emits useful warnings and errors about your XIB files right in the Xcode build window. I've found this to be very, very valuable when working with my XIB-based projects.
The NIB file produced by compiling a XIB file in ibtool is a deployment-only file. Unlike most earlier NIB files, one cannot extract a deployment NIB file from an application and open it in Interface Builder for inspection. This is slightly sad, since it makes it harder to learn how others did things. However, in recent years, it has rarely been a worthwhile learning experience to open deployed NIBs, since all one usually finds is a morass of "Custom View" panels.
XIB Wishlist
Interface Builder 3, XIBs, and the new capabilities of ibtool are a great leap forward in Mac development. I've been using XIB files exclusively in my Leopard-only development. I haven't yet converted FlickrExport to be XIB-based. They work perfectly for me, but I have heard of the occasional problem with opening a XIB-compiled NIB on Tiger, so I'm not sure that I'll adopt XIB files in code that has to be Tiger-compatible.
The one remaining thing I really want to see in this tool set is the ability to diff and ultimately merge XIB files, but I would be very happy to just get diff capabilities right now. It doesn't even need to be graphical - just a text report would be great. It seems that the XIB file format lays the foundation for something like that to happen in the future. Let's hope we get there.
Further Reading
There's not a huge amount about XIBs in there, but the Interface Builder 3.0 Release Notes are worth reading.
[Update: Jens Ayton pointed out that I had, incorrectly, used the term 'bundle' in a number of places to refer to NIB files which are, in fact, packages.]
What is the difference between a .xib file and a .storyboard?
Apple introduced the concept of
Pre-storyboard, each
You could refer this tutorial to get started.
Storyboard supports > iOS 5
"storyboarding"
in iOS5 SDK to simplify and better manage screens in your app. You can still use the .xib
way of development.Pre-storyboard, each
UIViewController
had an associated .xib
with it. Storyboard
achieves two things:.storyboard
is essentially one single file for all your screens in the app and it shows the flow of the screens. You can addsegues
/transitions between screens, this way. So, this minimizes the boilerplate code required to manage multiple screens.- Minimizes the overall no. of files in an app.
Storyboard
while creating a new project by leaving the "Use Storyboard" option unchecked.- Storyboarding replace the need for .xib files
- 1 .storyboard file = 'n' no of .xib files
- A storyboard is like a canvas where you put all your .xib files.
You could refer this tutorial to get started.
Storyboard supports > iOS 5
What aret the differences between a deep copy and a shallow copy?
Shallow copy (also know as Address Copy):
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copy:
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
If
B and A point to the same memory location
If
B and A point to different memory locations
B memory address is same as A's
B has same contents as A's

For a true deep copy (Array of Arrays) you will need
Shallow copy is also known as address copy. In this process you only copy address not actual data while in deep copy you copy data.
Suppose there are two objects A and B. A is pointing to a different array while B is pointing to different array. Now what I will do is following to do shallow copy.
Char *A = {‘a’,’b’,’c’};
Char *B = {‘x’,’y’,’z’};
B = A;
Now B is pointing is at same location where A pointer is pointing.Both A and B in this case sharing same data. if change is made both will get altered value of data.Advantage is that coping process is very fast and is independent of size of array.
while in deep copy data is also copied. This process is slow but Both A and B have their own copies and changes made to any copy, other will copy will not be affected.
[Ref: https://iphonecodecenter.wordpress.com/2013/08/26/difference-between-shallow-copy-and-deep-copy/ ]
References:
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copy:
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
If
B
is a shallow copy of A
, then it is like B = [A assign];
B and A point to the same memory location
If
B
is a deep copy of A
, then it is like B = [A copy];
B and A point to different memory locations
B memory address is same as A's
B has same contents as A's


Copy by default gives a shallow copy
That is because callingcopy
is the same as copyWithZone:NULL
also known as copying with the default zone. The copy
call does not result in a deep copy. In most cases it would give you a
shallow copy, but in any case it depends on the class. For a thorough
discussion I recommend the Collections Programming Topics on the Apple Developer site. initWithArray:CopyItems: gives a one-level deep copy
NSArray *deepCopyArray = [[NSArray alloc] initWithArray:someArray copyItems:YES];
NSCoding
is the Apple recommended way to provide a deep copy
For a true deep copy (Array of Arrays) you will need NSCoding
and archive/unarchive the object:NSArray *trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:oldArray]];
Other way of explanation
Shallow copy is also known as address copy. In this process you only copy address not actual data while in deep copy you copy data.
Suppose there are two objects A and B. A is pointing to a different array while B is pointing to different array. Now what I will do is following to do shallow copy.
Char *A = {‘a’,’b’,’c’};
Char *B = {‘x’,’y’,’z’};
B = A;
Now B is pointing is at same location where A pointer is pointing.Both A and B in this case sharing same data. if change is made both will get altered value of data.Advantage is that coping process is very fast and is independent of size of array.
while in deep copy data is also copied. This process is slow but Both A and B have their own copies and changes made to any copy, other will copy will not be affected.
[Ref: https://iphonecodecenter.wordpress.com/2013/08/26/difference-between-shallow-copy-and-deep-copy/ ]
References:
Wednesday, August 19, 2015
Sample code
func displayKeyboard(){
self.userInputTextField .becomeFirstResponder()
}
func disableKeyboard(){
self.userInputTextField .resignFirstResponder()
}
=========================
func getCurrentCurrencyData() -> Void{
let currencyURL = NSURL(string: "http://api.fixer.io/latest?base=USD")
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(currencyURL!, completionHandler: { (location: NSURL!, response:NSURLResponse!, error: NSError!) -> Void in
if(error == nil){
let dataObject = NSData(contentsOfURL: location)
let currencyDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary
let rates = Currency(currencyDictionary: currencyDictionary)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
var userInputStringValue: String = self.userInputTextField.text
var userInputDoubleValue : Double = NSString(string: userInputStringValue).doubleValue
if(userInputDoubleValue > 0){
var gbpCurrentValue = rates.gbp * userInputDoubleValue
var eurCurrentValue = rates.eur * userInputDoubleValue
var jpyCurrentValue = rates.jpy * userInputDoubleValue
var brlCurrentValue = rates.brl * userInputDoubleValue
var resultString = "UK Pounds - (GBP): " + gbpCurrentValue.description + "\n" +
"EU Euro - (Euro) : " + eurCurrentValue.description + "\n" +
"Japan Yen - (JPY) : " + jpyCurrentValue.description + "\n" +
"Brazil Reais - (BRL): " + brlCurrentValue.description as NSString
self.resultTextView.text = resultString as String
self.resultTextView.font = UIFont(name: "ArialMT", size: 15)
}
else{
self.resultTextView.text = "Please enter a valid dollar amount which is greater then 0"
}
})
}
else{
let networkIssueController = UIAlertController(title: "Error", message: "Unable to load data. Connectivity error!", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
networkIssueController.addAction(okButton)
// let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
// networkIssueController.addAction(cancelButton)
self.presentViewController(networkIssueController, animated: true, completion: { () -> Void in
//
})
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.resultTextView.text = "Unable to load data due to connectivity error! Please press the CONVERT button again to get the conversion rates!"
self.resultTextView.font = UIFont(name: "ArialMT", size: 15)
self.resultTextView.textColor = UIColor.redColor()
})
println(error)
}
})
downloadTask.resume()
}
self.userInputTextField .becomeFirstResponder()
}
func disableKeyboard(){
self.userInputTextField .resignFirstResponder()
}
=========================
func getCurrentCurrencyData() -> Void{
let currencyURL = NSURL(string: "http://api.fixer.io/latest?base=USD")
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(currencyURL!, completionHandler: { (location: NSURL!, response:NSURLResponse!, error: NSError!) -> Void in
if(error == nil){
let dataObject = NSData(contentsOfURL: location)
let currencyDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary
let rates = Currency(currencyDictionary: currencyDictionary)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
var userInputStringValue: String = self.userInputTextField.text
var userInputDoubleValue : Double = NSString(string: userInputStringValue).doubleValue
if(userInputDoubleValue > 0){
var gbpCurrentValue = rates.gbp * userInputDoubleValue
var eurCurrentValue = rates.eur * userInputDoubleValue
var jpyCurrentValue = rates.jpy * userInputDoubleValue
var brlCurrentValue = rates.brl * userInputDoubleValue
var resultString = "UK Pounds - (GBP): " + gbpCurrentValue.description + "\n" +
"EU Euro - (Euro) : " + eurCurrentValue.description + "\n" +
"Japan Yen - (JPY) : " + jpyCurrentValue.description + "\n" +
"Brazil Reais - (BRL): " + brlCurrentValue.description as NSString
self.resultTextView.text = resultString as String
self.resultTextView.font = UIFont(name: "ArialMT", size: 15)
}
else{
self.resultTextView.text = "Please enter a valid dollar amount which is greater then 0"
}
})
}
else{
let networkIssueController = UIAlertController(title: "Error", message: "Unable to load data. Connectivity error!", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
networkIssueController.addAction(okButton)
// let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
// networkIssueController.addAction(cancelButton)
self.presentViewController(networkIssueController, animated: true, completion: { () -> Void in
//
})
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.resultTextView.text = "Unable to load data due to connectivity error! Please press the CONVERT button again to get the conversion rates!"
self.resultTextView.font = UIFont(name: "ArialMT", size: 15)
self.resultTextView.textColor = UIColor.redColor()
})
println(error)
}
})
downloadTask.resume()
}
What are the differences between pixel and points in iPhone?
A pixel on iOS is the full resolution of the device, which means if I
have an image that is 100x100 pixels in length, then the phone will
render it 100x100 pixels on a standard non-retina device. However,
because newer iPhones have a quadrupled pixel density, that same image
will render at 100x100 pixels, but look half that size. The iOS
engineers solved this a long time ago (way back in OS X with Quartz)
when they introduced Core Graphics' point system. A point is a standard
length equivalent to 1x1 pixels on a non-retina device, and 2x2 pixels
on a retina device. That way, your 100x100 image will render twice the
size on a retina device and basically normalize what the user sees.
It also provides a standard system of measurement on iOS devices because no matter how the pixel density chanes, there have always been 320x480 points on an iPhone screen and 768x1024 points on an iPad screen.*
But at the same time, you can basically disregard the documentation considering that retina devices were introduced with iOS 4 at a minimum, and I don't know of too many people still running iOS 3 on a newer iPhone. But if such a case arises, your UIImage would need to be rendered at exactly twice its dimensions in pixels on a retina iPhone to make up for the pixel density difference.
It also provides a standard system of measurement on iOS devices because no matter how the pixel density chanes, there have always been 320x480 points on an iPhone screen and 768x1024 points on an iPad screen.*
But at the same time, you can basically disregard the documentation considering that retina devices were introduced with iOS 4 at a minimum, and I don't know of too many people still running iOS 3 on a newer iPhone. But if such a case arises, your UIImage would need to be rendered at exactly twice its dimensions in pixels on a retina iPhone to make up for the pixel density difference.
A pixel is a single square 'picture element' (hence pix-el), i.e. a
single dot in your image. A 10x10 image is made up of a set of pixels in
a grid 10 wide by 10 high, totaling 100 pixels.
The 'point' (pt) on the other hand is a unit of length, commonly used to measure the height of a font, but technically capable of measuring any length. In applications, 1pt is equal to exactly 1/72th of an inch; in traditional print technically 72pt is 0.996264 inches, although I think you'll be forgiven for rounding it up!
How many pixels = 1pt depends on the resolution of your image. If your image is 72ppi (pixels per inch), then one point will equal exactly one pixel.
The 'point' (pt) on the other hand is a unit of length, commonly used to measure the height of a font, but technically capable of measuring any length. In applications, 1pt is equal to exactly 1/72th of an inch; in traditional print technically 72pt is 0.996264 inches, although I think you'll be forgiven for rounding it up!
How many pixels = 1pt depends on the resolution of your image. If your image is 72ppi (pixels per inch), then one point will equal exactly one pixel.
What are the difference between “copy” and “retain”?
- Retaining and copying are two different things, the first is conceptually call-by-reference while the second is call-by-value
- Retain increases the retain count of an object by 1 and takes ownership of an object.
- Whereas copy will copy the data present in the memory location and will assign it to the variable so in the case of copy you are first copying the data from a location assign it to the variable which increases the retain count.
- Just remember that retain works on reference and copy works on value
- simple difference: whenever you write retain it will increment the count and whenever you write copy it will make reference and does not increment the count for example let say:-
In a general setting, retaining an object will increase its retain
count by one. This will help keep the object in memory and prevent it
from being blown away. What this means is that if you only hold a retained version of it, you share that copy with whomever passed it to you.
Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.
When dealing with
Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.
When dealing with
NSString
s in particular, you may not be able to assume that whoever is giving you an NSString
is truly giving you an NSString
. Someone could be handing you a subclass (NSMutableString
,
in this case) which means that they could potentially modify the values
under the covers. If your application depends on the value passed in,
and someone changes it on you, you can run into trouble.- assign
- assign is a default property attribute
- assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
- copy:
- copy is required when the object is mutable
- copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
- you need to release the object when finished with it because you are retaining the copy
- retain:
- specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
- if you write retain it will auto work like strong
- Methods like “alloc” include an implicit “retain”
I'm inferring from the presence of retain, that you're employing MRR (manual retain and release). In MRR, this code results in:
@implementation ABC
-(void) fun1
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount = +1
ObjectA * obj2 = obj1; // unchanged
// you have one instance of `ObjectA` with a retain count of +1
// both `obj1` and `obj2` point to the same single instance
}
-(void) fun2
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount = +1
ObjectA * obj2 = [obj1 retain]; // retainCount = +2
// you have one instance of `ObjectA` with a retain count of +2
// both `obj1` and `obj2` point to the same single instance
}
-(void) fun3
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount of `obj1` object = +1
ObjectA * obj2 = [obj1 copy]; // retainCount of `obj2` object = +1
// you have two instances of `ObjectA`, each with a retain count of +1
// `obj1` points to one instance and `obj2` point to the other
}
-(void) fun4
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount of `obj1` object = +1
ObjectA * obj2 = [obj1 mutableCopy]; // retainCount of `obj2` object = +1
// you have two instances of `ObjectA`, each with a retain count of +1
// `obj1` points to one instance
// `obj2` points to another instance, which is mutable copy of the `obj1` instance
}
@end
-(void) fun1
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount = +1
ObjectA * obj2 = obj1; // unchanged
// you have one instance of `ObjectA` with a retain count of +1
// both `obj1` and `obj2` point to the same single instance
}
-(void) fun2
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount = +1
ObjectA * obj2 = [obj1 retain]; // retainCount = +2
// you have one instance of `ObjectA` with a retain count of +2
// both `obj1` and `obj2` point to the same single instance
}
-(void) fun3
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount of `obj1` object = +1
ObjectA * obj2 = [obj1 copy]; // retainCount of `obj2` object = +1
// you have two instances of `ObjectA`, each with a retain count of +1
// `obj1` points to one instance and `obj2` point to the other
}
-(void) fun4
{
ObjectA * obj1 = [[ObjectA alloc] init]; // retainCount of `obj1` object = +1
ObjectA * obj2 = [obj1 mutableCopy]; // retainCount of `obj2` object = +1
// you have two instances of `ObjectA`, each with a retain count of +1
// `obj1` points to one instance
// `obj2` points to another instance, which is mutable copy of the `obj1` instance
}
@end
Clearly, in all of these cases, in MRR, if you don't do something with the ObjectA instances by the end of the method, you'll be leaking (because you're abandoning the last known reference to these objects). If using ARC, the necessary clean up is performed.
By the way, in the future, you should examine the results yourself. For example, if you added these diagnostic statements to the end of each method, you'd clearly see what's going on:
NSLog(@"%s: [obj1 (%p) retainCount] = %d", __FUNCTION__, obj1, [obj1 retainCount]);
NSLog(@"%s: [obj2 (%p) retainCount] = %d", __FUNCTION__, obj2, [obj2 retainCount]);
NSLog(@"%s: [obj2 (%p) retainCount] = %d", __FUNCTION__, obj2, [obj2 retainCount]);
That displays the address of the object to which the variable points, as well as the object's current retainCount. Needless to say, you shouldn't be using retainCount in production code, but it's useful solely for diagnostic purposes.
By way, while it's good that you're trying to understand the memory management, I would suggest that you seriously consider using automatic reference counting (ARC). It makes memory management much easier (no retain, release or retainCount). And if you're determined to stick with manual retain and release (MRR), then make sure you run your code through the static analyzer ("Analyze" on Xcode's "Product" menu), as it's pretty decent in identifying the sort of problems that plague MRR code.
References:
References:
Subscribe to:
Posts (Atom)