Pregunta

This may sound pretty strange to some people.. but I just went on to ask this.. Obviously, no one wants to do it.. but just to make the concept clearer, I want to ask. Usually we do it like this:

NSString *myString=[[NSString alloc]init];
NSString *myString=[NSString string];

As far as I understand, it gives a pointer object of NSString class, but, what if I do it like this:

NSString *myString=[[NSMutableString alloc]init];
NSString *myString=[NSMutableString string];

If this happens, what kind of class does "string" actually belong.. and since I have initialized it with a mutable class, can I send messages of NSMutableString class to "myString", which is an object of NSString class ?? Whatever the case is can I know what is the concept behind this.. also, this can be in the case of arrays, dictionaries and even many other calsses.

¿Fue útil?

Solución

Yes. The type of your object will be the one used by the alloc method. If you allocated with NSMutableString, then your object will be a member of NSMutableString class.

NSString *myString=[[NSMutableString alloc]init];

What's going on it's you have a pointer for the allocated object with the type of it's parent class, so the compiler will not see methods of NSMutableString and will get a warning if you try to call them directly.

But again, your object it's still a member of NSMutableString class, and it will respond to messages of NSMutableString class.

Even though you declared myString as a pointer to a NSString, you can perform this test the see what I'm talking:

BOOL test = [myString isKindOfClass:[NSMutableString class]]; //this will hold true

You can even perform a cast to do a method call explicit.

NSString *myString=[[NSMutableString alloc]init];
[(NSMutableString*)myString someNSMutableStringSpecificMethod];

PS: this counts not only for mutable / immutable objects, but for all specialization classes

Otros consejos

What happens on the second line is you get a NSMutableString object, but the reference is an NSString, you can only call messages on the reference's exposed interface, therefore the messages would be send to your NSMutableString object, BUT only the interface exposed by NSString would be visible.

You can however at any time cast it to a NSMutableString for example:

[((NSMutableString *)myString) appendString:@"anotherString"] // This works because of the cast

[myString appendString:@"anotherString"] // Compiler complains because it does not find that method in NSString interface.

and send messages exposed by NSMutableString interface.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top