开发者

Dictionaries, autorelease pools, and temporary objects

Let's say I have a dictionary full of objects for keys that may or may not be there. What is the standard practice for checking wh开发者_运维知识库ether this key exists or not?

For example, what I've written looks like this:

    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]];
    }

Should I surround this code with an autorelease pool? Do I have to release each time I point temp to an object in the dictionary, or does the pool handle that automatically? Is there a better way to handle errors?


I use the method described in this post: How to map JSON objects to Objective C classes?


objectForKey: does not return an autoreleased object, it returns a direct pointer to the desired object, therefore you do not need an inner autorelease pool here.

If the desired object is not found, objectForKey: will return nil, so that is what you should be testing here:

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

Also, it looks like you might want to declare those instance variables as retained properties if you're going to be doing this all over the place:

[ivar release];
ivar = ...;

Declare the properties in your .h file like so:

@property (nonatomic, retain) NSNumber *latitude;

Then you'd do this within your @implementation:

@synthesize latitude;

Once that's done, you can simply do the following instead:

self.latitude = temp;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜