InitWith 方法与工厂方法
我正在学习 ObjC 和 Cocoa,这也是我第一次认真涉足编程领域。
我无法理解 initWith 方法(在实例上调用)和工厂方法(在类上调用)之间的差异。
首先,为什么它们被称为“工厂”方法,以及我所说的“InitWith”方法是否有一个合适的术语?
其次,功能上有什么区别?这只是内存管理的影响(工厂方法返回一个自动释放的对象)吗?
例如,[NSString stringWithString: (NSString*)aString]
和 [[NSString alloc] initWithString: (NSString*)aString]
之间的真正区别是什么?
I'm picking up ObjC and Cocoa, which is also my first serious foray into programming in general.
I'm having trouble with the differences between initWith methods, which are called on instances, and factory methods, which are called on classes.
Firstly, why are they called "factory" methods, and is there a proper term for what I've dubbed "InitWith" methods?
Secondly, what's the functional difference? Is it just the memory management implications (that factory methods return an autoreleased object)?
For example, what's the real difference between [NSString stringWithString: (NSString*)aString]
and [[NSString alloc] initWithString: (NSString*)aString]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这些方法之间的区别在 Cocoa 的 对象所有权中进行了描述政策。您拥有从 -initWithString: 返回的对象,因此必须释放它,但您不拥有从 +stringWithString 返回的对象,因此不需要释放它(此外,如果您确实想获得它的所有权,则必须保留它)。
之所以调用工厂方法,是因为它们返回一个已经为您创建的对象,通常带有您提供的用于配置该对象的参数,以方便程序员。
The difference between the methods is described in Cocoa's object ownership policy. You own the object returned from -initWithString: and so must release it, but you don't own the object returned from +stringWithString and so do not need to release it (furthermore, if you do want to gain ownership of it, you must retain it).
Factory methods are called that because they return an already-created object for you, usually with parameters you provide that are used to configure the object, for the convenience of the programmer.
在您的示例中,
当您进行分配时,您会在内存中为字符串放置一个空间,因此分配。然后告诉它用等于 aString 的字符串进行初始化。 (NSString *) 是对象类型的标识符,因此您告诉它 aString 被声明为 NSString。
我通常会做类似
声明 aString 等于什么的事情。
如果您将某些内容分配到内存中以便管理它,您将需要在正确的时间释放它,例如
代码部分,
关于 NSString 的所有内容都可以在 Apple 的文档中进行解释
NSString
On your example of
When you do an alloc you are placing a space for the String in the memory hence the alloc. you then tell it to initialize with the string equal to aString. the (NSString *) is an identifier for the object type so you are telling it aString is declared to be an NSString.
I usually do something like
declares what aString is equal to.
If you alloc something into memory in order to manage it you will need to release it at the correct time such as the
section of your code
Everything about NSString can be explained in this documentation from Apple
NSString
主要区别在于,
返回一个自动释放的字符串,您无需担心其内存管理,而
返回一个您负责释放的字符串。基本上前者是后者的快捷方式,加上自动释放。
The main difference is that
returns an autoreleased string whose memory management you need not worry about, whereas
returns a string which you are responsible for releasing. Basically the former is a shortcut for the latter, plus autorelease.