I've been told that every time you allocate a variable, you have to release it. However, when I allocate a variable and then return it, there's no way to deallocate it. How do you release variables in this case or does the system auto-release them then?
Code:
(NSString *)sayHi:(NSString *)name {
NSString *myName = [NSString alloc] initWithFormat:@"Hi, %@", name];
// I can't release myName here, because then I wouldn't be able to return it.
return myName;
}
Here's another example:
Code:
(NSString *)norrisizeMe:(NSString *)name {
NSString *myName = [NSString alloc] initWithFormat:@"%@ Norris", name];
// I can't release myName here, because I need it!
return [NSString stringWithFormat:@"Hi, %@", myName;
}
I've been told that every time you allocate a variable, you have to release it. However, when I allocate a variable and then return it, there's no way to deallocate it. How do you release variables in this case or does the system auto-release them then?
Code:
(NSString *)sayHi:(NSString *)name {
NSString *myName = [NSString alloc] initWithFormat:@"Hi, %@", name];
// I can't release myName here, because then I wouldn't be able to return it.
return myName;
}
Here's another example:
Code:
(NSString *)norrisizeMe:(NSString *)name {
NSString *myName = [NSString alloc] initWithFormat:@"%@ Norris", name];
// I can't release myName here, because I need it!
return [NSString stringWithFormat:@"Hi, %@", myName;
}
That's (one of the reasons) why Obj-C (NSObject, actually) provides an 'autorelease' mechanism.