简体   繁体   中英

Usage of @property and weak properties in Objective-C

I have a specific question and I could not find an answer for it.

I have a storyboard which has some views. Some of the views have outlets. I understand that I have to declare my outlets as weak parameters however I don't know if I have to declare getters and setters (with @property and synthesize).

1 - __weak IBOutlet UITableView *table;
2 - @property(nonatomic, weak) UITableView *table; 

If I just declare (1) I can just do "table" on the view controller.

If I declare (1) and (2) I can do self.table.

What's the difference? What is the best approach?

(1) is an instance variable declaration. (2) is a property definition. If you synthesize the property, or use auto-synthesis, an instance variable is also created in that case. Usually, unless you want to expose the view in public API or for polymorphism, it is enough to declare an instance variable.

There are some other specific cases where a property may be preferred. For instance, if you want to reference a view inside a block but do not wish to retain self , a property is easier to access using the weakSelf paradigm. But you can create weak references to views also, so this is moot.

Accessing instance variables is not done using the dot ( . ) notation, but using directly or, less used, the arrow ( -> ) notation.

So either:

[_tableView reloadData];

or

[self->_tableView reloadData];

Remember that using -> on a nil reference results in a bad access.

你可以只为两者“表”,你只需要在你的实现中使用@synthesize来合成属性。

The first is an instance variable, the second one is defining a property. The convention is to always use properties, which now defaults to auto synthesize, with the iVar named on the convention _varName . You can then access the variable with _varName or with self.varName . It is recommended to always access variables through properties, the only exception being when you are overriding the property's getter.

There generally is no reason to declare an outlet as a strong property, implying ownership. Most views are owned by their superviews.

@property (weak) IBOutlet UITableView *table;

You then treat is as any other property

@synthesize table = _table;
- (void)someMethod
{
     [self.table doSomething ....]
}

See also Managing the Lifetimes of Objects from Nib Files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM