Pregunta

Desarrollando juegos de iPad. Me encuentro con esto. Este es mi código de muestra:

Método 1:

Foo.h

@interface Foo : UIView{
    UILabel *title;
    .... // Other objects like UISlider, UIbuttons, etc.
}

// I add @property for all the objects.
@property (nonatomic, retain) UILabel *title;

... blablabla

Foo.m
// I synthesize all the properties.
@synthesize title;
... blablabla

// Release in dealloc method
[title release];
....
[super dealloc];

Método 2:

Foo.h

@interface Foo : UIView{
    UILabel *title;
    .... // Others object like UISlider, UIbuttons, etc.
}
// But this time I didn't add @property, synthesize and release.

Foo.m
// When I need the label, I allocate it:
title = [[UILabel alloc] initWithRect: CGRect(10, 10, 100, 30)];
title.text = @"test";
[self addSubview: title];
[title release];

Tanto el método 1 como los 2 funcionan, pero ¿cuál es la diferencia entre los 2 métodos (el método2 tiene menos código)?

¿Qué método debo usar y por qué?

¿Tiene algo que ver con la gestión de la memoria?

¿Fue útil?

Solución

El método 2 es técnicamente incorrecto ya que enviando -release Para titular, indica que ya no está interesado en él. Debe hacerlo nulo inmediatamente después, o mejor aún, convertirlo en una variable local.

El método 1 está absolutamente bien y tiene la ventaja de que, fuera de -dealloc siempre que siempre use la propiedad para referirse a ella, no necesita preocuparse por obtener -retain y -release -Correcto.

Otros consejos

La diferencia es que, en el Método 2, no tendrá acceso al título desde fuera del objeto FOO. La variable de instancia es privada a la clase.

Además, debe asegurarse de equilibrar el asignación/retención y lanzamiento.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top