开发者

Do I have to use initWithString when allocated?

NSString *str = [开发者_StackOverflow中文版[NSString alloc]init];
str = [str initWithString:@""];

This code crashes. If I use like below, it is OK.

NSString *str = [[NSString alloc]initWithString:@""];

Can't I use initWithString after allocation?


You are re-initializing memory which was already initialized by way of your invocation of -init on the first line.

NSString objects are immutable, which means that their internal character buffer cannot be modified in any way. If you need this functionality, use NSMutableString.

Therefore, your code makes no sense to me because there is no way to modify the string, why create it with an empty string?

I suggest creating an NSMutableString object like so:

NSMutableString *str = [[NSMutableString alloc] init];

Then, you can muck around with the string with the various methods (-setString:, replaceCharactersInRange:withString:, etc.)

I don't see any other reason why you'd ever create a string (that you own no less), that is initialized with an empty buffer.


Your question suggests that you don't want to allocate and initialize the object on the same line of code. That would be the case when you have some kind of logic that would initialize it with different strings and that you want to put that logic between the allocation and the initialization.

The +alloc method is the method that allocates the objects, -init initializes it. There's no requirement that those methods are called together, although that's a common convention. Therefore, the following code is valid and allows you to put code between the allocation and the initialization:

NSString *str = [NSString alloc];
str = [str initWithString:@""];

A different solution that is fairly more common is to place the declaration of the pointer before the allocation, therefore the following is also valid.

NSString *str = nil;
str = [[NSString alloc] initWithString:@""];

Technically this will still allocate and initialize the object together, if you for some reason actually needs the object to be allocated and initialized on two separate lines I would recommend my first example.


This is correct:

 NSString *str = [[NSString alloc] initWithString:@""];

You are not supposed to call twice an init method on an object, like you are doing in your code. So, you just init when allocating.


NSString *str = [[NSString alloc] initWithString:@""];

is correct. Also remember that whenever you use alloc, copy or new you own the object and have to release it at some point with

[str release];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜