I’ve been watching CP193 classes on itunes and the common message that comes about is reusability.
I’m creating a program that has a list in the form of an NSMutableArray. I will be accessing this class over and over again.
So I created an NSMutableArray class with a function to setup NSStrings in the array
@interface Geology : NSMutableArray
- (void) setuparray;
In the implementation file I have
[super addobjects:@"object1"];
I would like to initialise this object with objects already inside. I imported the header file inside my ViewController with the following code:
Geology *geology = [[Geology alloc] initWithCapacity:5];
[geology setuparray];
NSLog(@"%@", [geology objectAtIndex:1];
However the program does not compile with the following error:
Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘* -[NSMutableArray initWithCapacity:]: method only defined for abstract class. Define – Geology initWithCapacity:]!
So from that I need to define the capacity inside my new file. However even though I add [Super initWithCapacity] inside the file it still does not work?
edit:
Geology.h
@interface Geology : NSMutableArray
- (void) setupGeology;
@end
Geology.m
@implementation Geology
- (void) setupGeology{
[super initWithCapacity:1];
[super addObject:@"object1"];
}
@end
In my ViewController I have
#import "Geology.h"
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
Geology *geology = [[Geology alloc] initWithCapacity:5];
[geology setupGeology];
NSLog(@"%@", [geology objectAtIndex:1]);
}
First of all you don’t have initWithCapacity declared and defined in your .h and .m since NSMutableArray is an abstract class, so you will need to have to define this and secondly I am not sure if this is the correct way to do it… Whenever you need to add extra functionality to an existing class you can always use categories in objective-c. Subclassing is uusally done when you need to add extra properties to a class along with some functionality.
I believe you should look into categories , because subclassing NSMutableArray is a very rare thing and I have never felt the need to do it.
You can refer to this answer for more clarity.