Question

I have a situation where I want to allocate a single NSString object, and assign text to it inside of an if-else block. When I write the code like this:

NSString *string = [NSString alloc];  
if (firstCase) 
    [string initWithString:@"firstCase"];  
else if(secondCase)
    [string initWithString:@"secondCase"];  
[self someFunction:string];

I get an error inside of someFunction (throws an NSInvalidArgumentException when I try to use string). Also, when I step through my code, once i enter someFunction, the console produces a line that says:

Did you forget to nest alloc and init?

which is referring to string.

I've tried the same thing using an NSMutableString and just doing string = [[NSMutableString alloc] init] and just appending to the string in each if-else block, but I was wondering if anyone knew why the previous way does not produce the same results.

Was it helpful?

Solution

Is it possible your running into a case where you are not meeting requirements for your if and else if?? you might want to double check what your cases are... or you might want to default your string to "". EDIT: you can then append to the string after you have declared it to some value using stringByAppendingString

NSString *string = [[NSString alloc] initWithString:@""];
if(case1)
   [string stringByAppendingString:@"desired string"];
elseif(case2)
   [string stringByAppendingString:@"other string"];

here is a link to apple's NSString class reference: http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top