discuss-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to initialise an array class inheriting from NSArray?


From: Chris B. Vetter
Subject: Re: How to initialise an array class inheriting from NSArray?
Date: Tue, 3 Jun 2003 19:56:47 -0700

On Wed, 4 Jun 2003 04:40:24 +0300
Christopher Culver <crculver@users.sourceforge.net> wrote:
> I've got a class that inherits from NSArray, but don't know how to 
> initialise it. Here's how it looks:
> @implementation NewClass : NSArray.
> [...]
> - (id) init
> {
>         self  = [super arrayWithObjects: @"String1", @"String2", nil];
>         return self;
> }
> However, when I compile this, gcc reports that "NSArray doesn't
> respond to arrayWithObjects". How then am I supposed to initalise this
> subclass?

The idea was correct, but you used the wrong method. +arrayWithObjects:
is a factory method, as indicated by the '+', so you would use it like

  NSArray *myArray = [NSArray arrayWithObjects: ...];

However, what you want is an instance methods, the ones starting with a
dash '-' ... in this case -initWithObjects:

  if( (self = [super initWithObjects: ...]) )
    return self;

> (And the reason this is a subclass is because I want to use it as a 
> data source for an NSTableView, for which I have to define two extra 
> methods, and this is the only way I know how at the moment. I hear 
> something called "categories" might be useful, but haven't learned 
> about this yet).

Categories are a way to extend an object's abilities. You can add new
methods to the object, but you _cannot_ add new instance variables.

The new methods are considered a part of the class you extend with a
category and subclasses will inherit all of the new abilities.

One possible use of categories is to create "private" methods. Similar
to defining plain C static functions "inside" your foobar.c you create a
private category like

  @interface MyCreativeClass (Private)
  - (void) someWeirdMethod;
  - (void) anotherFunkyMethod;
  @end

in your MyCreativeClass.m file (or a header file that's only included by
your creative class)

You might want to take a look at

http://wiki.gnustep.org/index.php/Objective-C%20Tutorials
http://wiki.gnustep.us/index.php?op=modload&name=phpWiki&file=index&pagename=Tutorials

for Objective-C tutorials that explain the details between Class,
Subclass and Categories (among other things ;-)

-- 
Chris




reply via email to

[Prev in Thread] Current Thread [Next in Thread]