I would like to define the following function in Objective-C. I have provided pseudo-code to help illustrate what I’m trying to do.
PSEUDOCODE:
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 who I assign it to results in a “BAD Access” error.
I don’t know what the difference between:
static NSstring *xx;
or the non-static:
NSString *xx;
declarations are, and how or why I would want to use one over the other.
I also do not fully understand the initializers of NSString, and how they differ. For example:
[[NSString alloc] initWithString:@"etc etc" ];
or the simple assignment:
var = @""
or even:
var = [NSString stringWithString:@"etc etc"];
Can you give me a hand please?
So far, using the NSString value returned from functions like those listed above, always causes an error.
That declares a statically allocated variable, much like it does in C.
Inside a method that declares a normal local stack variable, just as it does in C.
As you should be aware, the difference between the two is that the first will keep its value between invocations of the function (and can cause trouble if the function is called from multiple threads).
That creates a new NSString object, with the contents
etc etc. This may or may not be the same as any other NSString object in your program with the same contents, but you don’t have to care. Memory management wise, you own it, so you are responsible for ensuring that you eventually callreleaseorautoreleaseon it to avoid leaking memory.Those are basically the same. Both give you an NSString object with the contents
etc etc. This may or may not be the same as any other NSString object in your program with the same contents, but you don’t have to care. Memory management wise, you do not own it, so you must not callreleaseorautoreleaseon the object unless you first took ownership by callingretain. Also, since you do not own it, you can use it within your method, pass it as a parameter to other methods, and even use it as the return value from your method, but you may not store it in an ivar or static variable without taking ownership by callingretainor making a copy (withcopy).Also, note that
""and@""are very different. The first gives you aconst char *exactly as it does in C, while the second gives you an NSString object. Your program will crash if you use aconst char *where the code expects an NSString object.