objective-c - 在 objective-c 中为实例变量分配值

标签 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;  
}

为什么要分配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

对于方法中后面的NSArrayviewDidLoad不分配对象,因此该方法不负责在其上调用release。经验法则是,如果您对其进行alloc编码,则有责任确保其被发布。否则,这不是您的问题。

使用sortedArrayUsingSelector:方法对数组进行排序。选择器标识Objective-C中的方法。 @selector是选择器的文字语法(有点像@""NSString对象的文字语法)。因此,该代码所说的是“给我一个将components中的对象排序的数组,并在进行排序时使用compare:方法比较每个对象。对数组进行排序时,它将在其中的对象上调用compare:。确定如何将它们排列的数组。

关于objective-c - 在 objective-c 中为实例变量分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/683400/

相关文章:

objective-c - 如何在 SQLite 数据库与内存使用之间做出决定

ios - 在 iPad 上的 UIPageViewController 中强制使用纵向模式

python - 在获取或设置另一个类实例变量时,如何引用另一个类实例变量?

java - 实例变量初始化的问题

objective-c - 如何让 ARC 下的 OCMock 停止使用弱属性对 NSProxy 子类集进行 nilling?

iphone - 检查我的服务器上的 plist 的新版本

ios - 动态模拟 iOS 动态类型系统文本大小 (UIContentSizeCategory)

ruby-on-rails - 在 Rails 3 中初始化变量的位置

ruby - 直接在 ruby​​ 中使用实例变量是不好的形式吗?

c++ - 在其他类构造函数中使用参数化构造函数