问题描述
我是一个自我编程的人,所以我时不时地缺少一些基本知识.
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.
在Objective-c中,我可以看到如下代码行:
In objective-c, I can see lines of code like this :
aClassName *myObject = (aClassName *)[NSEntityDescription insertNewObjectForEntityForName:@"aClassName" inManagedObjectContext:app.managedObjectContext];
困扰我的是(aClass *)部分.这是什么 ?
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.
谢谢您的解释.
推荐答案
这是强制转换,在这种情况下是强制转换(即使因为强制转换是隐式的).
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.
考虑以下情况:
Class *a = [[Subclass alloc] init];
Subclass *b = a;
(假设Subclass
是Class
的子类)
这不会编译,因为a
是用子类中不包含的类型静态定义的.但是该分配不会动态地产生任何问题,因为在实践中a
用于存储Subclass
对象.
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.
那你做什么?您放置一个强制转换Subclass *b = (Subclass*)a;
来告诉编译器信任我,忽略对该赋值进行类型检查,我断言它将对运行时有效",然后自动删除编译错误.当然,强制执行此行为会从代码中删除类型安全性,因此您必须知道自己在做什么.
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..
在您的特定情况下,方法+(id)insertNewObjectForEntityForName:...
的返回类型为id
,这是ObjectiveC中最不特定的一种对象,如果不像普通的id
那样存储,则始终需要将其强制转换为某种对象
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
这篇关于Objective-C(aClassName *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!