AVFoundation - property declarations - basic question - iphone

I'm fiddling around with the AVCamDemo from Apple. Apart from trying to get my head around all that, I ran into something I don't understand.
The properties are initialized in a very strange way and I didn't find any explanation for this.
In the header-file
AVCaptureSession *_session;
...
#property (nonatomic,readonly,retain) AVCaptureSession *session;
in the .m-file
#synthesize session = _session;
What's the story with the underscore???
Thanks for any clarification!

Basically, you have two things going on here. an ivar (instance variable) and the property.
The ivar is the actual variable.
The property is syntactical sugar for getters and setters.
If you do
#synthesize session;
The ivar and the property are assumed to have the same name by the compiler.
if you do
#synthesize session = _session;
Then the property name is session and the ivar name is _session.
MY OPINION:
I've been doing Cocoa for over a decade. and #synthesize session = _session; is the safer way. Every now and then, the compiler or the programmer get confused when the ivar and the property have the same name.

The underscore is a naming convention to distinguish properties from instance variables.
In particular, it helps to distinguish between assignment to the property (that automatically decreases and increases the reference count) and assignment ot the instance variable (without automatic reference count update).

Related

#synthesize the "_" notation

It's clear that the #synthesize define the setter and getter for the object.
But it is unclear to me that:
#synthesize managedObjectContext = _managedObjectContext;
What does it mean? And why not just implement it in the following way:
#synthesize managedObjectContext;
which seems much easier?
Plus, is it related to the lazy programming, which means that you have to write the setter and getter urself?
Hope that someone could help;)
It's just a convention people use to give the property and the iVar separate names. The property will be called managedObjectContext and the iVar will be called _managedObjectContext.
If they both are named the same it can be fairly easy to confuse them, and mixing them up them can give unexpected results, since using the iVar name will bypass any setters and getters on the property.
Other than that, it has no real function.

In Objective-C, when should I use property and when should I use instance variable?

I'm not familiar with the program language which has both property and instance variable.
So I don't know good ways to use property and instance variable.
Now I use only properties in my Objective-C code and I don't use any instance variables.
Do I need to use instance variable?
Or using only property is the best practice for Objective-C?
#interface ViewController : UIViewController
{
// instance variable
#public
int a;
}
// property
#property(nonatomic, strong) NSString *b;
#end
The basic difference between variable and property is that, you can give attributes to property. You can not give any attributes to variable.
So, if you wish to have any specific behavior like retaining the variable, accessing it atomically, have access out side the class, you should go for the properties.
If you simply want to access the variable with in the class and no special behavior is attached to that variable, no need to access it via property. You can directly use variable itself. It will improve the performance also.
There are some advantages a #property has over an ivar:
Memory management : Behind the scenes it will create a setter which creates the variable with correct memory management. It will save you some headaches because you can easily see how the memory management is done (strong/weak and retain/copy/assign).
Accessibility from other classes: if you declare your #property in the .h and #synthesize it in the .m you ivar will be public readable and writeable. You can prevent this with a privat class extension. You even can declare a #property public readonly and declare them internally readwrite via a privat class extension.
Eg: a private property
// [In the implementation file]
#interface MyClass ()
#property (nonatomic, retain) NSMutableArray* someData; // private!!
#end
#implementation MyClass #synthesize someData
#end
Custom getter and setter: If you like you can still write custom getter and setters and you can even just write a getter or setter and let the other one automatically #synthesize. And you can write custom logic into such a getter and setter e.g. you can reload a tableview after a #property has changed.
Automatic Key-Value-Observing (KVO) compliant: If you use or planning to use KVO you get it basically for free by just declaring the property. Nothing else need to be done!
Dot notation: You can access getter and setter via dot notation if you have the #property.
self.myIvar = (id) someThing;
[array addObject:self.myIvar];
If you need you iVar to be public it is simpler to write one #property than writing a getter and setter for a iVar
With a #property you do not need to declare in iVar (in iOS and 64bit Mac Os X applications). You can do it via the #synthesize:
#synthesize myiVar = _myIvar;
Use properties everywhere. Don't even declare instance variables, but synthesize them like this: #synthesize myProperty = _myProperty in order to differentiate them from property names. Properties are good way to cope with memory management as well. The only place you must use the synthesized instance variable is in the dealloc method.
The advantages of the properties are a lot:
- The accessor methods define how will you get and set the value of your instance variable.
- You can customize the accessor methods (for example to lazy instantiate an ivar or do something when a setting a new value like setNeedsDisplay.
- You don't cope with memory management when setting a new value - the setter takes care for releasing/retaining (depending how have you declared the property - retain/copy/assign/strong.
- Some multithreading stuff with the atomic/nonatomic attributes
- You can take advantage of the KVO, when using properties
- And least, but not last - don't worry about performance issues if you have concernes that every time a getter or a setter is called...
A #property is an instance variable that has had some semantic sugar applied to it, to help expose it to the outside world (usually), and to help avoid writing boilerplate code for getting and setting it.
though properties are made generally when you need to access some variable outside of the class, mean getter n setter, but in objective C, an additional need to make property is that the memory management goes on compiler ends, so if you are using some object, not primitive data types, then you should use property and synthesize it, and then release in dealloc if you are using manual reference counting. but again the main objective to make properties it to access some iVar outside the class like passing parameters from one class to other etc.
If you #synthesize a #property, you will have access to a get and a set method, which are very convenient. You can also define how the setter will behave (retain, assign, copy) if it's nonatomic or atomic and if it's read only. If you don't specify anything (aka you don't synthesize the property) the ivar won't be visible outside of the class by default, but you can achieve this by using #public. Logically you can also define them as #private or #protected .
Normally I #synthesize a #property because I want to have access to the ivar from the outside of the class and also because I want a getter and setter methods.
The general opinion is that you should use properties whenever possible. If you're still in doubt, here is Apple's recommendation:
In general, you should use accessor methods or dot syntax for property access even if you’re accessing an object’s properties from within its own implementation, in which case you should use self.
...
The exception to this rule is when writing initialization, deallocation or custom accessor methods
...
You should always access the instance variables directly from within an initialization method because at the time a property is set, the rest of the object may not yet be completely initialized
Read the whole document here for a better understanding of the subject.
As for performance issues, for most apps the gain is insignificant. Read this for a very detailed description.

What exactly is a property in Objective C ? What is the difference between a property and an instance variable?

I am very much confused between instance variables and property. I have read number of posts regarding this but still i am not clear about it.
I am from JAVA background and what i infer from objective C documentation is that a property is similar to JAVA BEAN CLASS (one having getter and setter of instance varibles). A property can accessed from other classes through its getter and setter methods while an instance variable is private and cannot be accessed from other classes.
Am i right in thinking in this direction ?
The parallel with Java is very good. The only difference is that Objective C provides a way to access a property as if it were a variable, and Java does not. The other difference is that in Objective C you can synthesize properties, while in Java you need to write your getters and setters manually.
Property is a "syntactic sugar" over a getter method or a pair of a getter and a setter methods. Properties are often (but not always) backed by an instance variable, but they can be implemented in any way that you can implement a parameterless instance method.
Ok, instance variable and property is far away from each other. instance variable is a state of object and property is a assecor method(getter/setter) of that state(instance variable).
So whenever you create an property in header file. compiler convert those property in to accessor method. suppose you declared property - #property(nonatomic, assign, readwrite) NSString *name;
So compiler will be converted those in to
-(NSString *)name;
-(void)setName:(NSString *)name;
And then for definition for accessor method there is two way.
manually - use dynamic in implementation file(.m) and then give the definition of accessor method by doing this you won't get any warning.
Let compiler do the job - this can be done by synthesizing property e.g synthesize name;. so now compiler will generate the definition for the accessor method for you.
Hope it helps ;)
I know this subject has been beat to death here ... but some seem to be focusing on the technical details, whereas I wanted mention something along the lines of the BIG PICTURE ...
Think of properties as kind of first-class ivars. Both properties and ivars may model attributes of an object ... but an ivar gets special attention if you go ahead and set it up as a property. Basically, you should an attribute as a property (as opposed to an ivar) if you feel it needs getter / setter methods. Dot notation makes for very readable code. This may help in deciding when to declare a variable as a property as opposed to simply using a regular ivar.
A property in objective c is in fact the setter and getter methods that make it possible to access an attribute in a class from outside of it. So when you declare for example
#interface example:NSObject{
NSString *variable;
}
#property(readwrite, assign) NSString *variable;
#end
#implementation
#synthesize variable;
#end
You are in fact declaring the methods
-(NSString *)getVariable;
-(void)setVariable(NSString *)value;
And you can access then by using the point notation and the name of the property, like
instance.variable = something;
something = instance.variable;
The primary difference between instance variable and property is that for properties, the compiler will automatically generate a getter/setter method pair. For instance:
#property (nonatomic) int value;
will generate:
-(void)setValue:(int)i
{
value = i;
}
-(int)value
{
return self->value;
}
given #synthesized.
If you crab a book on Objective-C 1.0, you'll notice that this feature isn't available. This is a new feature in 2.0, also known as the dotted syntax. It's introduced mainly because the complicated getter/setter syntax.
The benefit of this feature is that even though you have the compiler automatically declared the pair for you, you can still manage to override it. For instance, you can still have -(void)setValue:(int)i declared as a method of your class, and override the behavior. This is useful in scenarios of validation, such as you want to put a limit on the range of value.
As far as Java is concerned, Objective-C actually do have #public instance variable syntax, but it's a habit not to use it. It's sort of similar to Java's concept of protecting a private variable through getter/setter. But its primary objective-c is to override getter/setter and minimize syntax.
Now this is just a preview, refer to http://cocoacast.com/?q=node/103 or some objective-c 2.0 books if you wanted to know more.
Well, maybe it was not clear that a property does not need an instance variable.
You can define a read-only property based on any calculation on instance variables or any other variables in the scope. The issue here is that you must manually code the getter.
#interface person:NSObject{
NSDate *birthDate;
}
#property(readonly) int age;
#end
#implementation
-(int) age{
// return calculated age based on birthDate and today;
}
#end
The name of the property does not need to be the same as the instance variable.
#synthesize myProperty = myVar;
I found this amazing thread which clearly explains each and evrything about properties.
http://www.iphonedevsdk.com/forum/iphone-sdk-tutorials/7295-getters-setters-properties-newbie.html
Thank you all for your responses.

When do I need to have both iVar and a property?

I see some examples sometimes would declare a property as well as variable other times they do not .e.g. some time I see code like this
#interface Test : NSObject
{
UIProgressView* _progressView;
}
#property (nonatomic,retain)UIProgressView* progressView;
#end
at other times I will come across
#interface Test : NSObject
#property (nonatomic,retain)UIProgressView* progressView;
#end
Why what are the reasons ? I am learning and almost always use property and variable both.
I have used UIProgressView just as example.
Using ivars instead properties is only useful if you want #protected access (access from subclasses only), or support the old runtime (which required both).
It depends whether the property is synthesized against an iVar or derived in some other way (or against another iVar).
IF we have an instance of the class - i.e:
Test *myTest = [[Test alloc] init];
Then basically the property declaration
#property (nonatomic,retain)UIProgressView* progressView;
is telling anyone interested in using the interface that they can access the following two functions on an instance of this class:
[myTest progressBar];
[myTest setProgressBar:aProgressBar];
And objective C also lets you use shorthand notation:
myTest.progressBar =
xxx = myTest.progressBar
which does exactly the same thing.
It is not necessary for these two methods to be implemented via an iVar of the same name as the property, or even via an iVar at all (they could do even do a database fetch or derive the value).
If you #synthesize the property (which means you want the precompiler to generate the above methods for you) and don't explicitly specify an iVar on the #synthesize directive, then the methods described above will automatically be generated (due to the synthesize method) to set or get the value to/from an iVar of the same name as the property (and the implementation will include retain/release logic depending on the property directive.
If you don't #synthesize the property then you provide your own implementation and it can be anything you want. It is also possible to #synthesize the property but include a directive to use a different iVar in the method definition:
#synthesize progressBar=someOtheriVar;
in which case you will not see an iVar of the same name as the property in the header file either.

Prefixing property names with an underscore in Objective C [duplicate]

This question already has answers here:
Closed 10 years ago.
I've previously avoided underscores in my variable names, perhaps a holdover from my college Java days. So when I define a property in Objective C this is what I naturally do.
// In the header
#interface Whatever
{
NSString *myStringProperty
}
#property (nonatomic, copy) NSString *myStringProperty;
// In the implementation
#synthesize myStringProperty;
But in almost every example it is done like
// In the header
#interface Whatever
{
NSString *_myStringProperty
}
#property (nonatomic, copy) NSString *myStringProperty;
// In the implementation
#synthesize myStringProperty = _myStringProperty;
Should I get over my aversion to the underscore because that is the one way it should be done, is there a good reason for this style being the preferred one?
Update: With automatic property synthesis nowadays you can leave out the #synthesize and the result is the same as if you'd used
#synthesize myStringProperty = _myStringProperty;
which clearly shows you Apple's preference. I've since learned to stop worrying and love the underscore.
I always use underscores. It creates a clear distinction between local variables and instance variables. It also avoids compiler warnings in the following situation:
#interface MyClass
{
NSString *name
}
#property (nonatomic, copy) NSString *name;
- (id) initWithName:(NSString *) name;
#end
#implementation MyClass
#synthesize name;
// The following method will result in a compiler warning
// (parameter name same as ivar name)
- (id) initWithName:(NSString *) name {
if (self = [super init]) {
self.name = name;
}
return self;
}
#end
EDIT:
After having to endure downvotes and reading through the comments, let me try to make my point:
Apple recommends that ivars have the same name as their property. Apple also recommends that properties start with a lowercase letter. And Apple also recommends that local variables start with a lowercase letter.
Now you have a problem, because when you read a piece of code, and you see a variable being used, you cant' tell by the naming convention if this variable is an ivar or a local variable. That sucks. The solution is to have different naming conventions for ivars and local variables. That's just plain common sense.
The way you implement this naming convention is irrelevant. If you really want, you can simply append "_WOOHAHA" to the ivar names. I don't care (but maybe others will). The thing is that people who know what they're doing have decided to go with the "underscore prefix" for ivars. IMHO, they made the right decision, even if their own company recommends something else. (the developers I'm talking about are the people writing some major Apple frameworks and the .NET Framework classes)
In the end, code quality is more important than following a stupid rule that isn't even followed by the people preaching it.
Another remark about the code you've shown: never use retain on string properties. You should use copy instead.
For more info about copy/retain on properties, see:
NSString property: copy or retain?
The naming convention for the instance variable prefixed by _ is now clearly stated by Apple in the "Coding Guidelines for Cocoa", after the revision of 2012-02-16, with its reason.
Make sure the name of the instance variable concisely describes the attribute stored. Usually, you should not access instance variables directly, instead you should use accessor methods (you do access instance variables directly in init and dealloc methods). To help to signal this, prefix instance variable names with an underscore (_), for example:
#implementation MyClass {
BOOL _showsTitle;
}
If you synthesize the instance variable using a declared property, specify the name of the instance variable in the #synthesize statement.
#implementation MyClass
#synthesize showsTitle=_showsTitle;
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html#//apple_ref/doc/uid/20001284-BAJGIIJE
The lecture in iTunes U, iPhone App Development CS193p Fall 2011 taught by Paul Hegarty at Stanford University, also explains this convention.
http://itunes.apple.com/itunes-u/ipad-iphone-application-development/id473757255
I'm aware of that this question is asked quite a while ago, but I myself had the same question and wanted to share my findings.
Current suggested Objective-C 2.0 practice is to use the same name for the ivar as the property. You can optionally assign a different ivar in the #property declaration, but the fact that by default, synthesized accessors for a property will access the ivar with the same name as the property indicates that's the pattern they expect you to follow.
No matter what, since objects still have to send messages to themselves to access properties, it's hard to confuse when you're accessing a property or when you're accessing its backing ivar directly, though using the 2.0 dot access to properties does make it more possible. Using the standard message passing syntax makes intent more explicit, IMO.
#interface Foo : NSObject {
NSNumber *bar;
}
#property(readwrite, retain) NSNumber * bar
#end
#implementation Foo
#synthesize bar;
-(void) baz {
NSNumber *numberOne = [NSNumber numberWithInt: 1];
//Both set the value of bar through either the your custom or the synthesized setter method
[self setBar:numberOne];
self.bar = numberOne;
//Both get the value of bar through your synthesized or your custom accessor method
NSNumber *fooBar = [self bar];
fooBar = self.bar;
//Both manipulate the bar ivar directly
bar = numberOne;
fooBar = bar;
}
#end
Apple reserves selectors beginning with underscore for their own "private" methods and that would include properties. I don't think they reserve _ for ivar names though.
Personally, I would steer clear of using underscore to start any kind of variable name. It's an opaque convention. What if somebody else uses underscore for locals and no underscore for instance variables? What if you accidentally omit the underscore in a method where you have a local defined with the same name?
It's much better to make your local names different from your ivar names. For example in a setter you might use newName or neWValue.
It is purely a style issue.
I don't know which examples use the underscored ivar style. The official Apple examples (e.g. CryptoExercise) do not prefix the ivars with _.
I will just point out that a new navigation project using core data uses trailing underscores by default and makes the variables private.
#interface MyTestAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UINavigationController *navigationController;
#private
NSManagedObjectContext *managedObjectContext_;
NSManagedObjectModel *managedObjectModel_;
NSPersistentStoreCoordinator *persistentStoreCoordinator_;
}
#interface RootViewController : UITableViewController <NSFetchedResultsControllerDelegate> {
#private
NSFetchedResultsController *fetchedResultsController_;
NSManagedObjectContext *managedObjectContext_;
}
The KVC part of the runtime expects either a name or _name ivar when using valueForKey: on an object when it cant find a message to retrieve that variable. see http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/SearchImplementation.html
If the runtime bothers to search for _name and the apple documentation mentions the _name first there might be a good reason for this. Let's take a look at some SDK classes: UINavigationBar.h this class has underscores in front of all ivars, UIView too... the list goes on. Well maybe it is that way with the new fangled iOS SDK and good ole NS* classes don't do thinges that way... wrong; they use the underscore as well in the header files.
Apple uses the underscore in private API messages as well as ivars. I can't understand why their examples do not push this behavior especially when the runtime bothers to have this so called "naming convention" hard coded into the variable search path. It would be nice to see some consistency.
Just a note, there is a strict naming scheme you have to follow to be KVC compliant; the link above helps you to conform to this to use this handy feature of the runtime.