How to determine the returned NSString function in Objective-C / Xcode using a temporary variable?

I would like to define the following function in Objective-C. I provided pseudo code to help illustrate what I'm trying to do.

PSEUDOKOD:

function Foo(param) {
  string temp; 

if(param == 1) then
  temp = "x";
else if(param == 2) then
  temp = "y";
else if(param == 3) then 
  temp = "z";
else
  temp = "default";
end if    

  return temp;
}

For some reason, if I do this ... the variable to which I assign it, will result in a "BAD Access" error.

I do not know what is the difference between:

static NSstring *xx;

or non-static:

NSString *xx;

ads, and how and why I would like to use one over the other.

I also do not quite understand the NSString initializers and how they differ. For instance:

[[NSString alloc] initWithString:@"etc etc" ];

or simple assignment:

var = @""

or even:

var = [NSString stringWithString:@"etc etc"];

Can you give me a hand?

So far, using the NSString value returned from functions like the ones listed above always causes an error.

+3
3
static NSstring *xx;

, C.

NSstring *xx;

, , , C.

, , ( , ).

[[NSString alloc] initWithString:@"etc etc"]

NSString etc etc. , NSString , . , , , release autorelease , .

@"etc etc"
[NSString stringWithString:@"etc etc"]

. NSString etc etc. , NSString , . , , release autorelease , , retain. , , , , ivar , retain ( copy).

, "" @"" . const char * , C, NSString. , const char *, NSString.

+8

:

- (NSString *)functionName:(int)param {
    NSString *result = nil;

    switch (param) {
        case 1:
            result = [NSString stringWithString:@"x"];
            break;
        case 2:
            result = [NSString stringWithString:@"y"];
            break;
        case 3:
            result = [NSString stringWithString:@"z"];
            break;
        default:
            result = [NSString stringWithString:@"defaultv"];
            break;
    }

    return result;
}
+8

Put the real code, not the pseudo-code, as it greatly simplifies the answer to your question in specific terms.

Given that you indicate that you are completely new to Objective-C, I would suggest starting with the language guide , and then moving on to the memory management guide .

+2
source

All Articles