开发者

Grow a NSMutableArray with NSNumber objects

Sorry for the newbie question, but I need a NSMutableArray with some NSNumber inside, created dynamically in a for cycle. My code looks like this:

for (...){
NSNumber *temp_number = [[NSNumber alloc] initWithInteger:someNSInteger];
        [target_array addObject:[temp_number copy]];
        [temp_number release];
}

Is this 开发者_开发问答a correct way to do it? Does it leak?

Thanks! Miguel


Yep, that leaks. You want:

NSNumber *temp_number = [[NSNumber alloc] initWithInteger:someNSInteger];
    [target_array addObject:temp_number];
    [temp_number release];

So, no copy. The logic is that because you use alloc, you end up owning temp_number. You then add it to the array and the array does whatever it needs to. You've used temp_number for its intended purpose, so you no longer want to own it and release it.

If you were to take a copy, that would create another instance of NSNumber, which you also own, and therefore which you should also release when you're finished with.

In practice, the array (if it's allocated and exists, rather than being nil), will retain the object for itself, but that's an implementation detail specific to that class and not something you should depend upon or even be particularly interested in beyond the contract that says that the objects you add can later be found in the array.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜