What is the difference between arrayWithObjects and initWithObjects?

前端 未结 3 1144
借酒劲吻你
借酒劲吻你 2020-12-18 02:45

Can you please explain me exact difference between these two lines?

NSArray *foo = [NSArray arrayWithObjects:@\"hai\",@\"how\",@\"are\",@\"you\",nil];
NSArra         


        
相关标签:
3条回答
  • 2020-12-18 02:46

    You own the second array but not the first.

    0 讨论(0)
  • 2020-12-18 02:47

    arrayWithObject returns an autoreleased array so you do not have to worry about releasing it when you don't need it anymore (but if you store it in an instance variable, you should retain it to prevent the autorelease pool from freeing it). initWithObject returns an array with a retain count of 1, i.e. you own the array and you must release it at some point to prevent memory leaks.

    You might want to read this guide for more clarification.

    0 讨论(0)
  • 2020-12-18 02:58

    arrayWithObjects is "convenience constructor".

    It will do:

    return [[[NSArray alloc] initWithObjects:@"hai",@"how",@"are",@"you",nil] autorelease]
    

    for you.

    It is just a convenience method to get an autoreleased object while improving the readability of the statement. Keep in mind that the fact that the object is autoreleased is a simple convention of the language (not a rule, so you could do differently, but I would not suggest that).

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