Is it better to only create an instance variable for a control or an instance variable with a prope开发者_如何学编程rty in objective c/xcode?
If you are to create a property is it best to make it atomic or nonatomic (for a control).
For example, what is the best practice for doing the following:
@interface blah
{
UILabel *label;
}
@property (nonatomic, retain) IBOutlet UILabel *label;
OR
@interface blah
{
IBOutlet UILabel *label;
}
OR
@interface blah
{
UILabel *label;
}
@property (retain) IBOutlet UILabel *label;
Then when I dealloc is it best to do:
[self.label release]
or [label release]
EDIT:
So to summarize...
- When referencing controls in you code, you should use instance variables
- In dealloc, you can release the controls by [iVal release]\
I wouldn't create a property for label since it doesn't need to be accessed outside of UIViewController, hence I'd use second case. The thing regarding atomicity - logic dictates that since UI should be updated from main thread only, UILabel should be accessed only in main thread too. So it virtually doesn't matter if you declare your property nonatomic
or atomic
, you'd access and alter that UILabel
var only from main thread.
Performance-wise, nonatomic
properties are faster too since access does not need to acquire lock.
If you're using the interface builder, then declaring
IBOutlet UILabel *label;
alerts the IB that there is a label that can be linked. This allows you to modify the label you create in the IB using the pointer label
. However, if the label will never need modification, then there is no need to declare it or reference it at all. Simply create it in the IB and leave it at that. In this case there is no need for getter or setter methods, and so no need to use @property
or @synthesize
at all.
If you're creating and configuring the label entirely programmatically, then there is no need to declare it as an IBOutlet
. Just use
UILabel *label;
and then adjust the label
as you like in your code. The IB need not know it exists. Then create getter and setter methods if you need them.
You want to avoid using method calls in your dealloc method. You might run into a condition where your getter accesses another one of your instance variables that may have already been released. It's safer to just release the instance variable.
[label release];
And if you do decide to release via the accessor, then use the following (as stated by fichek):
self.label = nil;
精彩评论