Actually I am from java background and I am learning objective c.I am very confused about strange behaviour of objective C."Please Read 3rd Question its important one."
Questions are provided in sequence so please give answers in sequence as its understandable to me and others.
Question 1
I have two classes derived from NSObject
: A
and B
:
@interface A : NSObject
@end
@interface B : NSobject
-(void)display; // It displays "I am class B"
@end
Now if I do this:
A *a = [[B alloc]init]; // Show warning not error (it must be illegal)
[a display]; // prints "I am class B"
It calls the display method of class B. I don't think that it should happen because:
A
doesn't have the methoddisplay
. By polymorphism.This could be a security threat as I am creating reference of any class and passing object of any another class and accessing data by it.
There could be design issues as
Dog
class instance gets an object ofPrinter
class and now i am callingprint
method onDog
instance.I have reference of
NSArray
and passed object ofNSMutableArray
and now i am callingNSMutableArray
method on this instance.[nsarr addObject:@:abc]; //Looking very odd
Question 2
If I have Foo
protocol and if any class is not confirming it. It should not be allowed to get object of that class in protocol reference.
@protocol Foo
@required
-(void)abc;
@end
If i call:
id<Foo> obj= [[B alloc]init]; // Shows warning ignore it for now as it must be illegal also
[obj display]; // It will call display method which should be illegal
- It should not happen, as
B
is not conforming to protocolFoo
andobj
is takingB
object and callingB
instance method. I think its very bad because of polymorphism and security
Question 3
If my class has a class method which returns an object of that class which is not autoreleased, the compiler shows warning. If I pass the object returned by that class (not conforming protocol) method to reference of protocol. (IT SHOULD BE AN ERROR).
id<Foo> obj = [Abc aClassMethodReturnsObjectWhichNotAutoreleased]; //show warning
It shows a warning which is good. Abc
did not conform to the protocol Foo
BUT
id<Foo> obj = [NSArray arrayWithObjects:@"abc",@"def",nil]; // It does **not** show a warning as it will return autorelease object. NSArray doesn't conform protocol Foo
Why does the above assignment to the NSArray
class not show a warning as it is showing in the previous example.
Thanks in advance.
EDIT
*Answer 3rd Question:*As NSArray returns id object which will allow to pass in "id obj" but in "aClassMethodReturnsObjectWhichNotAutoreleased" case the method returns "ABC *" pointer so that is why compiler giving warning in this case.