NSString *str = [[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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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.
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.