我正在查看的功能:
-(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;
}
为什么要分配NSDictionary,然后将其分配给名为* dictionary的指针,然后再分配给实例变量stateZips?为什么不分配它并将其直接分配给实例变量并节省创建和释放另一个NSDictionary的内存?始终遵循相同的方法,包括稍后在此函数中使用NSArray ...
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.statesZips = dictionary;
[dictionary release];
同样,这种排序将哈希表(字典)中的键按字母顺序排列。我不确定我是否明白这一行:
NSArray *sorted = [components sortedArrayUsingSelector:@selector(compare:)];
最佳答案
似乎没有人解决以下事实:
self.statesZips = dictionary;
不是直接的实例变量分配。
stateZips
是一个属性,因此代码行调用setStateZips:
方法。该方法保留或复制了字典,因此,除非viewDidLoad
方法打算出于某种目的再次使用它,否则不再需要它。这样就可以release
了。上一行:
[[NSDictionary alloc] initWithContentsOfFile:plistPath];
分配一个对象。这使您有责任在不再需要它时对其进行
release
编码。将其分配给statesZips
属性后,就不再需要它了,因此它已发布,您不应再使用dictionary
。您会注意到,以后的代码仅引用self.stateZips
,而不是dictionary
。对于方法中后面的
NSArray
,viewDidLoad
不分配对象,因此该方法不负责在其上调用release
。经验法则是,如果您对其进行alloc
编码,则有责任确保其被发布。否则,这不是您的问题。使用
sortedArrayUsingSelector:
方法对数组进行排序。选择器标识Objective-C中的方法。 @selector
是选择器的文字语法(有点像@""
是NSString
对象的文字语法)。因此,该代码所说的是“给我一个将components
中的对象排序的数组,并在进行排序时使用compare:
方法比较每个对象。对数组进行排序时,它将在其中的对象上调用compare:
。确定如何将它们排列的数组。
关于objective-c - 在 objective-c 中为实例变量分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/683400/