Reputation: 488
I have this class:
@interface G2Matrix : NSObject
...
- (id) initWithArray:(float *)val;
...
@end
This line below give me a warning saying that the first argument to the method initWithArray has an incompatible pointer type:
float m[16];
...
G2Matrix* matrix = [[[G2Matrix alloc] initWithArray:m] autorelease];
If I change the method name to something like initWithArray1 the warning disappears. I know that some objects in foundation classes have a method with the same name, but I am deriving from NSObject, which doesn't have this method. What gives?
Additional info - I call the same initWithArray method from other init methods in the G2Matrix class, but I don't see the warning there.
Upvotes: 2
Views: 737
Reputation: 7327
At a guess, this is a type problem:
Inside the other init methods, you call [self initWithArray:...]
. self
is typed as a G2Matrix*
. In this context the compiler can fully resolve which imp
(C function pointer) will eventually handle the method call, and detect its signature (argument and return types) correctly.
Out in regular code, [G2Matrix alloc]
returns an id
. In this context the compiler can only tell the method selector, which will be bound to an imp
at runtime. It has to guess which initWithArray:
you mean, and as you can see from the warning it guesses wrong, since a foundation class has an initWithArray:
method with a different signature. Your code does still work, the compiler just can't be certain.
Picking a unique name for the initMethod (initWithFloats:
maybe?) is the recommended way to shut the warning up. Other ways are: break it into two lines; or cast the alloc return value to the right class:
G2Matrix *matrix = [G2Matrix alloc];
matrix = [[matrix initWithArray:pointerToFloats] autorelease];
// or
G2Matrix* matrix = [[(G2Matrix *)[G2Matrix alloc] initWithArray:m] autorelease];
Looks a little odd, but allows you to turn the treat-warnings-as-errors compiler flag back on.
Upvotes: 3
Reputation: 10011
@tathagata thats because initWithArray is method defined in NSArray class so you cannot use it unless you subclass NSArray class.
see the documentation on NSArray
PS. by use the method, i meant Override the existing method for your purpose which is not a good idea you can find the Subclassing Notes in the document.
Upvotes: 0