Objective-C (aClassName *)

后端 未结 3 1010
迷失自我
迷失自我 2021-01-28 21:46

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,

3条回答
  •  被撕碎了的回忆
    2021-01-28 22:34

    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:

    Class *a = [[Subclass alloc] init];
    Subclass *b = a;
    

    (assume that Subclass is a subclass of Class)

    This won't compile because a is statically defined with a type which is not contained in Subclass. But the assignment wouldn't create any problem dynamically because a is used to store a Subclass object 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:... is id, which is the least specific kind of object in ObjectiveC, it always needs to be casted to something if not stored just like a plain id

提交回复
热议问题