I’m a kind of self-programmer-made-man, so I’m missing some basic knowledge from time to time.
That’s why I’m unable to really define well the topic of my question, because I don’t know how to name it and how it works (but I know answer will seem trivial to many of you). When you know what’s you’re looking for it’s a lot easier to find answers.
In objective-c, I can see lines of code like this :
aClassName *myObject = (aClassName *)[NSEntityDescription insertNewObjectForEntityForName:@"aClassName" inManagedObjectContext:app.managedObjectContext];
What’s bother me is that (aClass *) part. What’s this ?
I know/feel it’s related to very basic knowledge but I can’t name it so I can’t find it.
My guess (and that’s how I use it up to now) is that’s used for calling class methods (+) but i’m not sure of it and it may be more deep that what I understand.
Thanks for any explanation.
It’s a cast, in this case a down cast (even because up casts are implicit).
A cast is an operation that the developer does while writing the code to hint the compiler that a type is narrower than the one the compiler is thinking about.
Think about the following situation:
(assume that
Subclassis a subclass ofClass)This won’t compile because
ais statically defined with a type which is not contained in Subclass. But the assignment wouldn’t create any problem dynamically becauseais used to store aSubclassobject in practice.So what you do? You place a cast
Subclass *b = (Subclass*)a;to tell the compiler “trust me and ignore typechecking that assignment, I assert that it will be valid a runtime”, and you automagically remove the compilation error. Forcing this behaviour of course removes type safety from your code, so you must know what you are doing.Of course to understand the meaning of a cast in this situation you must at least know about inheritance and objects..
In your specific situation the return type of the method
+(id)insertNewObjectForEntityForName:...isid, which is the least specific kind of object in ObjectiveC, it always needs to be casted to something if not stored just like a plainid