views:

757

answers:

4

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

+1  A: 

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.

Ken
A: 

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.

Dave DeLong
+2  A: 

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 :-).

Nathan de Vries
Hmmm... It's Immutable? Well I need to send each object in the new array an extra release message (used alloc init) so there are no leaks. How do I release all the objects in an immutable array?
RexOnRoids
objects are retained by the array when they are added, so when the array is released, the objects inside should be released as well
slf
Why do you need a new array just to send a release message to the objects? Immutable means the ARRAY cannot be changed, you can always change (or send messages to) objects inside the array...Or better yet, autorelease objects before you add them to the array and then you do not have to worry about anything.
Kendall Helmstetter Gelner
A: 

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

lowell