Cra*_*aig 2 objective-c instance-variables
我正在看的功能:
-(void)viewDidLoad {
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"statedictionary" ofType:@"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.statesZips = dictionary;
[dictionary release];
NSArray *components = [self.stateZips allKeys];
NSArray *sorted = [components sortedArrayUsingSelector:@selector(compare:)];
self.States = sorted;
NSString *selectedState = [self.states objectAtIndex:0];
NSArray *array = [stateZips objectForKey: selectedState];
self.zips = array;
}
Run Code Online (Sandbox Code Playgroud)
为什么分配NSDictionary,然后分配给一个名为*dictionary的指针,然后分配给实例变量stateZips?为什么不分配它并将其直接分配给实例变量并节省创建和释放另一个NSDictionary的内存?始终遵循相同的方法,包括后来在NSArray的此功能中......
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.statesZips = dictionary;
[dictionary release];
Run Code Online (Sandbox Code Playgroud)
此外,此排序按字母顺序放置哈希表(字典)中的键.我不确定我理解这一行:
NSArray *sorted = [components sortedArrayUsingSelector:@selector(compare:)];
Run Code Online (Sandbox Code Playgroud)
似乎没有人解决这条线的事实
self.statesZips = dictionary;
Run Code Online (Sandbox Code Playgroud)
不是直接的实例变量赋值.stateZips是一个属性,因此该代码行调用该setStateZips:方法.该方法保留或复制字典,因此除非该viewDidLoad方法打算再次出于某种目的使用它,否则不再需要它.这样就可以了release.
上一行:
[[NSDictionary alloc] initWithContentsOfFile:plistPath];
Run Code Online (Sandbox Code Playgroud)
分配一个对象.release一旦你不再需要它,这就是你的责任.将它分配给statesZips属性后,不再需要它,所以它已经发布,你不应该再使用dictionary了.您会注意到以后的代码只引用self.stateZips,而不是dictionary.
在NSArray方法后面的情况下,viewDidLoad不分配对象,因此该方法不负责调用release它.经验法则是,如果你alloc这样做,你有责任确保它被释放.否则,这不是你的问题.
对数组进行排序使用该sortedArrayUsingSelector:方法.选择器标识Objective-C中的方法.这@selector是选择器的文字语法(有点像对象@""的文字语法NSString).所以,那段代码说的是"给我一个数组,其中的对象components被排序,并compare:在你进行排序时使用该方法来比较每个对象.当它对数组进行排序时,它将调用compare:数组中的对象确定如何将它们整理好.
| 归档时间: |
|
| 查看次数: |
9611 次 |
| 最近记录: |