(iOS) Gestión de memoria para variables temporales

So the standard rule is if an object is created with alloc, copy or retained, it needs a subsequent release. Objects created with convenience methods are autoreleased. But what about temp vars defined with "=" and used in the scope of a method? eg

NSError *error = nil;
NSString *tempString = @"foo";
int number = otherInt * 32;
NSUInteger row = [indexPath row];
NSArray *sameArrayDifferentPointer = otherArray;

o incluso

NSArray *sameArrayDifferentPointer = (*NSMutableArray) otherMutableArray;

I know the last one is 'bad' but compiles fine and doesn't throw exceptions.

preguntado el 10 de marzo de 12 a las 03:03

2 Respuestas

But what about temp vars defined with "=" and used in the scope of a method?

The same rules apply. Did you alloc, copy o el retain those values? I don't see a single alloc, copy o el retain in the examples you provided. Therefore, no release necesario.

respondido 10 mar '12, 03:03

error, number y row aren't objects (or pointers to objects) so they don't need to be (and indeed can't be) released. (number es un int, row is either an unsigned int or an unsigned long, error is a pointer to nil.)

tempString will be autoreleased—the line

NSString *tempString = @"foo";

es el equivalente de

NSString *tempString = [NSString stringWithString:@"foo"];

Writing it the second way makes it clearer what's going on. Likewise, your arrays are the equivalent of calling [NSArray arrayWithArray:otherArray].

respondido 10 mar '12, 03:03

How is the second case better? There's nothing at all wrong with assigning a constant string to a variable. - Caleb

Of course not. And you're assigning a constant string to a variable in both versions. The more verbose one makes it clearer what's happening, which can be helpful for clarity. But my statement that the second is 'usually better' was probably too strong—will edit. - Gabriel Roth

Makes perfect sense. Very new to Objective-C and even C in general and the concept of pointers still tricks me up. Thanks. - TijuanaKez

Just one last thing, what happens if error is passed as a reference to a method such as stringWithContentsOfURL:encoding:error and error is no longer nil. - TijuanaKez

@GabrielRoth Different strokes, I guess. I tend to prefer the simpler version. Also, assuming that the two are equivalent is a mistake. It happens that when you pass a constant string to +stringWithString (o -copy) you get the same pointer back, but that's an implementation detail that you shouldn't rely on. - Caleb

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.