与使用alloc和init声明NSString以及使用@"myString"进行分配之间的区别在于: [英] Difference bewteen declaring a NSString with alloc and init and assigning with @"myString"

查看:81
本文介绍了与使用alloc和init声明NSString以及使用@"myString"进行分配之间的区别在于:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我对Objective-C的一个小理解问题感到困扰.以Aaron Hillegass的书为例,我想知道如何为类的init方法中的NSString分配一个类似于此示例的值(对于了解这本书的人,该值用于RaiseMan):

Currently I'm troubled with a small understanding issue on Objective-C. As example following Aaron Hillegass's book, I'm wondering about assigning an NSString in the init method of a class a value like in this example (For people who know the book, this is used in the Person class of RaiseMan):

- (id)init
{
   if(![super init])
     return nil;
   myString = @"New entry";
   return self;
}

该字符串不是我分配的,因此通常我不必为释放它而烦恼.

This string isn't allocated by me, so normally I shouldn't bother about releasing it.

但是!此字符串的设置方法中会发生什么?按照内存管理规则,该方法应如下所示:

BUT! What happens in a setter-method of this string? Following the memory management rules the method should look like:

- (void)setMyString:(NSString *)newString
{
    if(myString != newString) {
        [myString release];
        [newString retain];
        myString = newString;
    }
}

[myString release]为什么起作用?我在某处读到,分配了= @"bla"的字符串无法释放.

Why does [myString release] work? I've read somewhere, that with = @"bla" assigned strings can't be released.

= @"bla"初始化是正确的方法吗?还是应该改用allocinit?

And is initializing with = @"bla" the right way? Or should I use alloc and init instead?

感谢您的帮助:)

推荐答案

NSString *constantString = @"constantString";

constantString这样的

字符串据说来自private(?)类NSConstantString,它们在程序的整个生命周期中都有效.偏离路线的释放并保留工作,(这意味着它们不会给您例外或崩溃),他们什么都不做.

String like constantString are said to be from a private(?) class NSConstantString and they are alive through all your program life. Off-course release and retain work, (in the mean that they won't give you a exception or crash) They just do nothing.

此处

您也曾在评论中说过,这将是{@property(..., copy) NSString myString;,但是您向我们展示的是典型的@property(..., retain)

Also you said in one of your comments that it would be a{@property(..., copy) NSString myString;But what you are showing us is a typical @property(..., retain)

这篇关于与使用alloc和init声明NSString以及使用@"myString"进行分配之间的区别在于:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆