NSString 初始化
这里是 Objective-C 菜鸟。
为什么会这样:
NSString *myString = [NSString alloc];
[myString initWithFormat:@"%f", storedNumber];
导致以下异常 -length 仅为抽象类定义。定义 -[NSPlaceholderString length]!
当这工作正常时:
NSString *myString = [[NSString alloc] initWithFormat:@"%f",storedNumber];
我认为后者只是前者的缩写(但我显然错了,至少根据编译器来说)。
Objective-C noob here.
Why would this:
NSString *myString = [NSString alloc];
[myString initWithFormat:@"%f", storedNumber];
results in the following exception -length only defined for abstract class. Define -[NSPlaceholderString length]!
When this works just fine:
NSString *myString = [[NSString alloc] initWithFormat:@"%f", storedNumber];
I would think that the latter is merely a contraction of the former (but I'm obviously wrong, at least according to the compiler).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为
-initWithFormat:
返回的对象与+alloc
返回的对象不同,即与myString
指向的对象不同>。这就是为什么您应该始终将+alloc
与-init...
结合起来的原因。这种情况在
NSString
等类集群中很常见。+alloc
返回一个通用字符串对象,然后-initWithFormat:
决定NSString
的具体子类,释放由创建的当前对象+alloc
,从 NSString 的具体子类创建一个新对象,然后返回这个新对象。Because
-initWithFormat:
is returning an object that’s different from the one returned by+alloc
, i.e., an object that’s different from the one pointed bymyString
. That’s the reason why you should always couple+alloc
with-init…
.This situation is common in class clusters such as
NSString
.+alloc
returns a generic string object, then-initWithFormat:
decides upon a concrete subclass ofNSString
, deallocates the current object created by+alloc
, creates a new object from a concrete subclass ofNSString
, and then returns this new object.或者
or