Suggest the best way of initialization of array ( or other objects )

后端 未结 4 686
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 09:07

I am a bit confused in the following two ways of initialisations.....

Way 1:

- (void) myMethod{

    NSArray *myArray = [[NSArray alloc] initWithObje         


        
相关标签:
4条回答
  • 2021-01-15 09:30

    When using method 2 (autorelease) the object is released when the operating system feels it has no references. But when using the manual release, as you typed in your code, you can release directly, or whenever you need to.

    0 讨论(0)
  • 2021-01-15 09:38

    Your second example uses a convenience constructor, which returns an autoreleased object. The question, then, is whether it's better to use autorelease or alloc/release. mmalc's answer on this StackOverflow thread explains the drawbacks of autoreleasing objects. (Basically, use alloc/release whenever possible.)

    Also (this may be stating the obvious), some classes might not have convenience constructors, so when working with these you'd have to use alloc/release.

    0 讨论(0)
  • 2021-01-15 09:41

    as i know,

    [NSArray arrayWithObjects:obj1,obj2,nil];
    

    returns an autoreleased object, smth like

    [[[NSArray alloc] initWithObjects:obj1,obj1,nil] autorelease];
    

    and I prefer not to manage memory with autorelease pool. maybe it's just a prejudice))

    0 讨论(0)
  • 2021-01-15 09:52

    I usually prefer the second way, and if I recall correctly, this is also what the Apple docs reccommend (use autorelease where possible).

    In Way 1 the memory gets released faster, so if you have a method that gets called in a loop or recursively, using autorelease may accumulate much memory, whereas alloc/retain will keep your memory footprint low.

    On the other hand I assume that using autorelease is more efficient, because the autorelease pool can release a big chunk of memory at once, instead of small chunks again and again. Tough I may be wrong here.

    0 讨论(0)
提交回复
热议问题