开发者

How to manage int when it's incremented inside another loop?

I have a simple loop with an int counter that gets incremented inside a while loop when a special case开发者_JAVA百科 exists. My question is simply - how should I manage memory inside this function with regards to the int specifically? I've been using NSNumber almost exclusively and what little time I've spent with int seems to make me think I'm not doing releasing it correctly.

Any other improvements are also welcome but I'm very interested in the int question

- (NSArray *)parseJson:(NSArray *) items
{
  NSMutableArray* hats = [[NSMutableArray alloc] init];
  NSEnumerator *enumerator = [items objectEnumerator];
  NSDictionary* item;
  int counterz = 0;
  while (item = (NSDictionary*)[enumerator nextObject]) {
    Hat* hat = [[Hat alloc] init];

    hat.addr = [item objectForKey:@"Address"];

    BOOL* hasHat = [item objectForKey:@"HasHat"];

    if ([hasHat boolValue]) {
      if (counterz < 10) {
        [hats addObject:hat];
        counterz++;
      }
    }
  }

  return hats;
}

Thank you in advance!


You don't need to release a "normal" (i.e.: non-object based) int - it'll happily life out its (brief, tragic) life on the stack until it falls out of scope.


You've got a couple unnecessary things and some memory leaks...

- (NSArray *)parseJson:(NSArray *) items {
  NSMutableArray *hats = [NSMutableArray array];
  int counter = 0;
  for (NSDictionary *item in items) {
    Hat *hat = [[Hat alloc] init];
    [hat setAddr:[item objectForKey:@"Address"]];
    BOOL hasHat = [[item objectForKey:@"HasHat"] boolValue];
    if (hasHat && counter < 10) {
      [hats addObject:hat];
      counter++;
    }
    [hat release];
  }
  return hats;
}

And heck, once you reach a counter of 10, you could break out of the loop, because you're never going to do anything useful once 10 is reached.

Some other comments:

  • The name of the method is wrong. Nothing about this method has to do with parsing JSON. At best you're interpreting an array of dictionaries that happened to originate from a JSON string, but there's nothing about the nature of this code that says "this is parsing JSON".
  • -[NSDictionary objectForKey:] returns an object. A BOOL is not an object, it's a primitive (like an int or char). Appending * to the type does not make it an object either. :)
  • Since the method name does not begin with new or alloc and does not contain the word copy, you're supposed to return an autoreleased object from it. The method in the question was returning an owned object (+1 retain count), since you invoked alloc, but never autorelease. Using the convenience constructor +array fixes this.
  • In your loop, you allocated a Hat object, but never released it. This is a classic memory leak.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜