Declaring IBOutlet inside or outside #interface? - objective-c

sorry If am I being too picky on this one but I am learning iOS programming now and I've seem some people who declare the IBOutlet like this:
IBOutlet attached to property
#import <UIKit/UIKit.h>
#import "CustomCell.h"
#interface CustomTableViewController : UITableViewController {
CustomCell *customCell;
}
#property (nonatomic, retain) IBOutlet CustomCell *customCell;
#end
And some declaring like this:
IBOutlet attached to the declaration inside the interface
#import <UIKit/UIKit.h>
#import "CustomCell.h"
#interface CustomTableViewController : UITableViewController {
IBOutlet CustomCell *customCell;
}
#property (nonatomic, retain) CustomCell *customCell;
#end
which one is the proper way to declare it? Are any differences between them?
If someone know to explain why do they put it on different places it would be awesome to learn.
Thanks a lot :)

Both of those are still "inside the interface" so your title it a bit confusing but I see what you are asking.
In many cases the result of either approach will be the same but they are different. An IBOutlet property will call the property's setter method which gives you an opportunity to override that setter if setting that property should have some side effect.
I prefer to use outlets on properties because I think it makes the memory management of the objects loaded from the nib much clearer. Take a look at memory management of nib objects and I think you will see what I mean.
Objects in the nib file are created with a retain count of 1 and then autoreleased. As it rebuilds the object hierarchy, UIKit reestablishes connections between the objects using setValue:forKey:, which uses the available setter method or retains the object by default if no setter method is available. This means that (assuming you follow the pattern shown in “Outlets”) any object for which you have an outlet remains valid. If there are any top-level objects you do not store in outlets, however, you must retain either the array returned by the loadNibNamed:owner:options: method or the objects inside the array to prevent those objects from being released prematurely.
IBOutlet ivars will call setters for those ivars if they exists and directly retain the object loaded from the nib if no setter is found.
Advertising the property as the IBOutlet at least makes it clear that the property's setter will always be used and follow whatever memory management rule has been set for that property.
Finally I argue that IBOutlets are part of the public interface of a class and it is therefore better to expose methods (via a property) for working with them eager than using -setValue:forKey: to manipulate the backing ivars which should be an implementation detail.

The two styles are interchangeable, there is no difference in the generated code or the way objects will be loaded from a nib. Really.
However, both styles have a redundant line. Simply leave out the ivar declaration. Just the line
#property (nonatomic, retain) IBOutlet CustomCell *customCell;
is sufficient in the modern runtime.
If you have a complex project, I suggest moving all the outlets out of the public interface into a separate header file. Most outlets are private interface, the only reason to have them in a header is so Interface Builder can find them.

You can declare both ways, there is no difference actually.
But, here is the thing:
If you need your class to have some ivar with a special behavior or it has to be accessed from outside, etc, and it has to be a property, then I will say you have 2 options to choose from (attached to the property and inside the class interface).
If that is not your case, don't create a property, is not necessary, just do it inside your class interface.
Hope it helps ;)

Related

How should I document property setters?

I occasionally override the setters of Objective-C properties, and was wondering. If I change the default behavior of a method drastically, where should I document this in the header? Or should I just use a new method completely?
In my current case, I am setting a view up as a placeholder view in interface builder. Programatically, there will be a way to replace this view with a new view (Either an icon, or an arbitrary custom view). The method to swap out the placeholder view will automatically set the property to the new view, remove the placeholder view from the parent view, add the new view to the parent view, and reposition/resize the new view appropriately.
I came up with three options:
A) Override the setter of the property, and document along with the property:
// Documentation goes here
// The setter of this property actually does <etc>
#property (nonatomic, retain) IBOutlet UIView* placeholderView;
B) Override the setter, and declare it in the header:
// Documentation goes here
-(void)setPlaceholderView:(UIView*)view;
C) Use a completely different method and set the property to readonly:
#property (nonatomic, retain, readonly) IBOutlet UIView* placeholderView;
-(void)replacePlaceholderView:(UIView*)view;
Option C seems appealing, because it makes it quite clear what the method does. It will also be clear that since it is different than a normal setter, it may act differently (which it will). The disadvantage I see here is that it doesn't seem to follow the normal Objective-C trend.
What do you guys think is the cleanest way to do something like this?
You shouldn't "change the default behavior of a [setter] method drastically" at all. A setter method should set a property, and if it does, you don't need to document the override in the header anywhere, since it does exactly what the user would expect, and the override is an implementation detail that can be documented in the implementation file. Radically changing expected behavior is only going to sow confusion, and is something to avoid. Go with option (C) unless your desired behavior is what a user would reasonably expect to happen when she sets that property.
In practice, an IBOutlet should only be set during initialization from nib files. If I was to refactor this, I'll declare the properties
#property (nonatomic, weak) IBOutlet UIView *initialPlaceholderView;
#property (nonatomic, weak) UIView *placeholderContainerView;
#property (nonatomic, weak) UIView *currentPlaceholderView;
then rename replacePlaceholderView: to
-(void)updatePlaceholderContainerWithNewView:(UIView*)newPlaceholderView;
This is self-documenting code. You can already assume the behavior just by the property and method names.

Noob properties error

I'm working with an existing code.
Here a popovercontroller has been declared in .h file and its giving me error in implementation line.
.h file
#property (nonatomic, strong) VFImagePickerController *imagePicker;
#property (nonatomic, strong) UIPopoverController *popoverController;
#property (nonatomic, strong) UINavigationController *targetVC;
.m file:
Please suggest how to fix this.
It appears that your class is a subclass of UIViewController. UIViewController has a private, undocumented ivar of _popoverController. Since you are trying to create an ivar in your class with the same name, you are getting an error.
The easiest thing to do is to rename your popoverController property to something different. Otherwise your app might get flagged for using a private API.
This problem occurs because your superclass, UIViewController, already has an instance variable named _popoverController. As a result, neither the default synthesis nor your explicit (commented) #synthesize directive have access to the instance variable that they want to use to provide the popoverController property.
You can resolve this by either renaming your property, or explicitly synthesizing the property to use a different instance variable name:
// Either
#property (nonatomic, strong) UIPopoverController *localPopoverController
// Or
#synthesize popoverController = _localPopoverController;
(Also note that the "local" prefix isn't necessarily best practice for your property names or instance variables; take a second to consider your preferred naming convention and pick a property/instance variable name appropriately.)
Uncomment the synthesize line and remove underscore to look like this: #synthetize popoverController;
And replace every _popoverController var name in your .m file to popoverController
Do not name your instance variable (or property) popoverController. As mentioned above UIViewController has an instance variable declared as _popoverController. (Who knows why.)
It would be wise not to give your popover controller a generic name anyway, because, for example, if you decide to add more than one popover to a toolbar, you'll have to create more than one popover controller to accomplish this.
If you look at Apple's sample code, you can see how they do this:
http://developer.apple.com/library/ios/#samplecode/Popovers/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010436
Check out the private properties section in DetailViewController. There, you will see three controller objects and none with the generic name "popoverController”. That will cause problems.

Properties vs. Instance Variables

I am confused as to why some classes declare a property but do not declare an ivar and vice versa.
Is it standard practice when declaring an instance variable to also declare it as a property as well?
Example:
#interface AppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *navigationController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
is just standard practice when declaring a class's ivar to make it a property as well?
I get that the #property creates its own elongated setter (and getter with #synethesize) but why does it need to be an ivar as well?
It doesn't.
In the old days, ivars were required to be declared in the #interface. This is actually still true for PPC and i386 (i.e. 32-bit intel) targets. This is because of the fragile base class problem, which required that all subclasses know the exact size of their superclass. As such, ivars need to be in the #interface or nobody can subclass the class.
With the move to x86_64 and ARM, alongside obj-c 2.0 came a fix for the fragile base class problem. With this fix, class sizes no longer need to be known at compile time but can be deferred to runtime. Therefore, ivars can be declared in other places. Notably, an ivar can now be synthesized from a #property (more specifically the #synthesize line in the implementation). In Clang they can also be declared in a class extension block (which looks like #interface ClassName ()) or directly on the #implementation.
Today, there are 3 reasons why you find ivars declared in #interface blocks:
Old code (or programmers with old habits) that hasn't been updated to take advantage of the ability to hide ivar declarations.
Code that needs to run on PPC or i386.
Code that, for whatever reason, wants their ivars to be public. This should never be the case.
When writing code today that doesn't need to target the old runtime, you should either synthesize your ivars from your properties (preferred), or if you need ivars that aren't tied to properties you should declare them in a class extension or on your #implementation. The primary reason for this is because the header file documents the public API of your class and should not contain anything that's not public. Ivars are not public, and therefore should not be in the header file.

Objective C - Defining an instance variable when defining a property

I saw this code snippet on the Internet (http://iphonedevelopment.blogspot.com/2008/12/outlets-property-vs-instance-variable.html):
#import <UIKit/UIKit.h>
#interface MyViewController : UIViewController {
UILabel *myLabel;
}
#property (nonatomic, retain) IBOutlet UILabel *myLabel;
#end
My question is...When #synthesize is called isn't the UILabel instance variable created automatically? What is the point of creating the instance variable in the header file.. Can you get away with just the #property?
When #synthesize is called isn't the UILabel instance variable created automatically?
Yes.
What is the point of creating the instance variable in the header file.
Personal preference. Some developers (like me) prefer to see a complete picture of the state of a class. It helps to see what instance variables are available, as well as check that all instance variables are released correctly.
It's also a relatively new feature. Older code wouldn't expect automatically-generated instance variables.
Can you get away with just the #property?
No, you need to #synthesize to get an automatically generated instance variables A property value that's generated programmatically would not map directly to any instance variable.
#synthesize will create the instance variable but you will not be able to see it in the debugger which can be downright inconvenient.
Consider filing a bug with Apple about this.
Yes you can get away with just the #property in Objective-c 2.0.
see: Do declared properties require a corresponding instance variable?

What is the difference between IBOutlet as a property or as a variable?

There are two different methods to declare IBOutlet.
In #interface section as variable:
IBOutlet UIButton *exampleButton;
Below the curve bracket but before #end of .h file as property:
#property (nonatomic, retain) IBOutlet UIButton *exampleButton;
What is the difference between these two methods and where should I use each one? Which method is better and in what cases?
Either one works fine in my experience. What doesn't work is declaring both the instance variable and the property "IBOutlet" -- that seems to really confuse things. If for some reason you want to avoid providing public access to your outlet, you can declare it as an instance variable and simply not create the property. On the other hand, now that the runtime will synthesize instance variables for you, many people are declaring only properties and skipping the explicit instance variable declaration; in that case, you'd obviously declare the property as the IBOutlet.
The #property combined with #synthesize setup the getter and setter methods for your objects. You should define it at least in the interface, and if you decide to create a property from it then you must also synthesize it the .m file.