iPhone Dev - NSString Creation

ⅰ亾dé卋堺 提交于 2019-12-20 07:48:38

问题


I'm really confused with NSStrings. Like when should I do

NSString *aString = @"Hello";

of should it be:

NSString *aString = [[NSString alloc] initWithString:@"Hello"];

But then its different when you're assigning a value to an NSString property isn't it? Can someone clear this up for me?

Thanks!!


回答1:


In general you should do the first, but they are mostly functionally the same. You can treat constant NSStrings just like normal NSString string objects, for instance:

[@"Hello" length]

will return 5. You can assign them to properties, everything just works. The one thing you might notice is that with the constant NSStrings you don't have to worry about retain/release. That is because they are actually mapped into the applications readonly data section, and don't have allocated memory. Retain and release calls against them still work, they just become noops.




回答2:


NSString *aString = @"Hello";

Will create an autoreleased string. That is, if you don't explicitly retain it, it will might disappear after your method is over (and sometimes that's totally fine). But if you want to hold on to it past that time, you'll need to retain it.

If you create a property for that string like this

@property (retain) NSString *aString;

And then assign like this:

self.aString = @"Hello";

Then you've properly retained the string and it will stick around.

On the other hand, using alloc, init will create a string for you with a retain count of 1, and if you don't need it past that method, you should release it.

****Edit: @"Hello" is not an autoreleased string, as others have pointed out. My bad. ****



来源:https://stackoverflow.com/questions/1210319/iphone-dev-nsstring-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!