gpt4 book ai didi

ios - 定义ivar的最佳方式是什么?

转载 作者:行者123 更新时间:2023-11-28 19:54:50 25 4
gpt4 key购买 nike

我定义了三个属性,一个 UISearchBar,NSDicitonary 类型和 NSArray 类型。

它们之间有什么区别? ( self 。)或(_)

原因是什么?

@property (nonatomic, strong, readwrite) UISearchBar  *searchBar;
@property (nonatomic, strong) NSDictionary *citiesDataDic;
@property (nonatomic, strong) NSArray *initialOfCity;

第一种方式:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *key = [_initialOfCity objectAtIndex:section];
NSArray *citySection = [_citiesDataDic objectForKey:key];
return [citySection count];
}


- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"citydict"
ofType:@"plist"];
_citiesDataDic = [[NSDictionary alloc] initWithContentsOfFile:path];
_initialOfCity = [[_citiesDataDic allKeys] sortedArrayUsingSelector:@selector(compare:)];

_searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
_searchBar.placeholder = @"enter words";
_searchBar.delegate = self;
[_searchBar sizeToFit];
}

第二种方式:

   NSString *key = [self.initialOfCity objectAtIndex:section];
NSArray *citySection = [self.citiesDataDic objectForKey:key];
return [citySection count];

[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"citydict"
ofType:@"plist"];
self.citiesDataDic = [[NSDictionary alloc] initWithContentsOfFile:path];
self.initialOfCity = [[self.citiesDataDic allKeys] sortedArrayUsingSelector:@selector(compare:)];

self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
self.searchBar.placeholder = @"enter words";
self.searchBar.delegate = self;
[self.searchBar sizeToFit];

最佳答案

readwrite

这个限定符是不必要的,因为它是默认行为。不要使用它,否则可能会使人感到困惑。

self. 语法调用属性的 getter 和 setter,可以通过 propertyNamesetPropertyName 明确定义。

尝试使用 self. 语法,因为如果有一天您需要 getter 或 setter,它会使事情变得更容易。通过 _ 语法访问属性将直接访问属性,即使定义了 getter/setter。

关于ios - 定义ivar的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27097481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com