【问题标题】:Dictionaries, autorelease pools, and temporary objects字典、自动释放池和临时对象
【发布时间】:2011-08-19 17:33:51
【问题描述】:

假设我有一本字典,其中包含可能存在或不存在的键的对象。检查此密钥是否存在的标准做法是什么?

例如,我写的内容是这样的:

    id temp;

    temp = [dict objectForKey: @"id"];
    if (temp != [NSNull null]) {
        uid = [temp intValue];
    }

    temp = [dict objectForKey: @"name"];
    if (temp) {
        [name release];
        name = [[NSString alloc] initWithString: temp];
    }

    temp = [dict objectForKey: @"latitude"];
    if (temp != [NSNull null]) {
        [latitude release];
        latitude = [[NSNumber alloc] initWithDouble: [temp doubleValue]];
    }

    temp = [dict objectForKey: @"longitude"];
    if (temp != [NSNull null]) {
        [longitude release];
        longitude = [[NSNumber alloc] initWithDouble: [temp doubleValue]];
    }

我应该用自动释放池包围这段代码吗?每次将 temp 指向字典中的对象时是否必须释放,还是池会自动处理?有没有更好的方法来处理错误?

【问题讨论】:

  • 我相信如果对象不在字典中,那么会返回nil,而不是NSNull对象。

标签: ios objective-c memory-management autorelease


【解决方案1】:

我使用这篇文章中描述的方法:How to map JSON objects to Objective C classes?

【讨论】:

  • 谢谢,这真的很有帮助!
【解决方案2】:

objectForKey:返回一个自动释放的对象,它返回一个指向所需对象的直接指针,因此你确实需要一个内部自动释放池。

如果没有找到所需的对象,objectForKey: 将返回 nil,因此您应该在这里测试:

id obj = [dict objectForKey:@"someKey"];
if(obj == nil) {
   //not found
}

此外,如果您要在各处执行此操作,您可能希望将这些实例变量声明为保留属性:

[ivar release];
ivar = ...;

.h 文件中声明属性,如下所示:

@property (nonatomic, retain) NSNumber *latitude;

然后你会在你的 @implementation 中这样做:

@synthesize latitude;

完成后,您只需执行以下操作:

self.latitude = temp;

【讨论】:

  • 谢谢,这是非常有用的信息。但是最后一部分是什么意思,“将这些实例变量声明为保留属性”?基本上,在我进入这部分代码之前,我已经分配并初始化了变量,所以如果没有找到它,当其他类试图访问这个时,我仍然会有一个空的 NSString 或诸如此类的东西。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 2014-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
  • 2010-10-22
相关资源
最近更新 更多