Reputation: 891
I have created an object of type NSMutableArray
#import <Foundation/Foundation.h>
@interface MyCustomObject : NSMutableArray
{
}
@end
in one of my classes, I delcare an instance:
MyCustomObject *myObj = [[NSMutableArray alloc] init];
But xcode is giving a warning on this line: Incompatible pointer types initializing 'MyCustomObject *' with an expression of type 'NSMutableArray *'
Any idea what is wrong? It works fine, but just wondering why it is throwing a warning and how to resolve it?
Upvotes: 2
Views: 232
Reputation: 237010
Firstly, as everyone else has said, you need to instantiate your class if you want an instance of your class. Evidently the reason you're not doing this is because you tried instantiating your class and it didn't work. That's the deeper problem: You can't simply subclass NSArray or NSMutableArray. As noted in the documentation, NSArray is a class cluster, which is basically a short way of saying "NSArray doesn't actually implement most of its methods."
In order to subclass NSArray, you essentially have to provide all of its functionality yourself. It is generally much easier to either create a category on NSArray or create a custom class that has an array as a member.
Upvotes: 3
Reputation: 2127
It should be:
MyCustomObject *myObj = [[MyCustomObject alloc] init];
if you do:
NSMutableArray *myObj = [[MyCustomObject alloc] init];
It will create an istance of MyCustomObject, but you will have a NSMutableArray pointer, so your new instance will just be seen as a NSMutableArray.
In this case:
MyCustomObject *myObj = [[NSMutableArray alloc] init];
It is an error. In previows a MyCustomObject can ben seen as a simple NSMutableArray. but a NSMutableArray cannot ever be seen as a MyCustomObject. It is a simple inheritance property.
Maybe this can help
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
Upvotes: 2
Reputation: 108
You should be instantiating the object as:
MyCustomObject *myObj = [[MyCustomObject alloc] init];
Otherwise, all you're doing is making an NSMutableArray and don't need your custom object (since none of its functionality would work.)
Upvotes: 2
Reputation: 52728
Try allocating a MyCustomObject
instead:
MyCustomObject *myObj = [[MyCustomObject alloc] init];
Upvotes: 0
Reputation: 1397
You can assign a child class to a variable typed as its super-class, but you cannot assign a super-class to a child class variable.
So, you'd want to:
MyCustomObject *myObj = [[MyCustomObject alloc] init];
Upvotes: 3
Reputation: 7336
I think you've got things backwards. MyCustomObject is a NSMutableArray, but NSMutableArray isn't a MyCustomObject. Your variable myObj should be a NSMutableArray if it needs to be able to hold both NSMutableArrays and MyCustomObjects.
Upvotes: 2