what does -arrayWithArray actually DO?

前端 未结 4 598
执笔经年
执笔经年 2020-12-16 04:27

I want to see EXACTLY how it creates an array. How can I view the .m files that show how it\'s done?

相关标签:
4条回答
  • 2020-12-16 04:56

    No, Cocoa is not open source.

    If you have a question, you should just ask it.

    This would be one valid way to implement it:

    + (id)arrayWithArray:(NSArray *)array {
        return [[[self alloc] initWithArray:array] autorelease];
    }
    

    You can read the GNUStep source for NSArray, but be aware that this is an alternate implementation of the Cocoa APIs.

    0 讨论(0)
  • 2020-12-16 05:01

    As @Ken mentioned, you can't see the source (although you can disassemble the method via gdb).

    The method itself creates an immutable (can't be changed), autoreleased copy of the given array. The following are identical in behavior:

    // Both resulting arrays are immutable and won't be retained
    NSArray* immutableArray = [[[NSArray alloc] initWithArray:mutableArray] autorelease];
    NSArray* immutableArray = [NSArray arrayWithArray:mutableArray];
    NSArray* immutableArray = [[mutableArray copy] autorelease];
    

    Pick whichever one you like based on brevity, I guess :-).

    0 讨论(0)
  • 2020-12-16 05:12

    GNUstep, the GNU implementation of the OPENSTEP spec from which Cocoa and Cocoa Touch descend, implements +arrayWithArray: as follows:

    /**
     * Returns a new autoreleased NSArray instance containing all the objects from
     * array, in the same order as the original.
     */
    + (id) arrayWithArray: (NSArray*)array
    {
      id    o;
    
      o = [self allocWithZone: NSDefaultMallocZone()];
      o = [o initWithArray: array];
      return AUTORELEASE(o);
    }
    

    http://svn.gna.org/viewcvs/gnustep/libs/base/trunk/Source/NSArray.m?view=markup

    0 讨论(0)
  • 2020-12-16 05:16

    If you're asking what's the purpose of +arrayWithArray (besides being an autorelease wrapper around -initWithArray), I'd say it's this: Use it when you want to create an autoreleased copy of an array. In other words, you could see it like this:

    NSArray * original = /* ... */;
    NSArray * newArray = [NSArray arrayWithArray:original];
    

    Is equivalent to:

    NSArray * original = /* ... */;
    NSArray * newArray = [[original copy] autorelease];
    

    I'd say it's there for convenience to use when it fits your style.

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