Tengo un objeto NSMutableArray
(retenido, sintetizado como todos) que se inicia muy bien y puedo agregar objetos fácilmente mediante el método addObject:
. Pero si deseo reemplazar un objeto en un índice determinado con uno nuevo en ese NSMutableArray
, no funciona.Cómo reemplazar un objeto en un NSMutableArray en un índice dado con un nuevo objeto
Por ejemplo:
ClassA.h
:
@interface ClassA : NSObject {
NSMutableArray *list;
}
@property (nonatomic, copy, readwrite) NSMutableArray *list;
@end
ClassA.m
:
#import "ClassA.h"
@implementation ClassA
@synthesize list;
- (id)init
{
[super init];
NSMutableArray *localList = [[NSMutableArray alloc] init];
self.list = localList;
[localList release];
//Add initial data
[list addObject:@"Hello "];
[list addObject:@"World"];
}
// Custom set accessor to ensure the new list is mutable
- (void)setList:(NSMutableArray *)newList
{
if (list != newList)
{
[list release];
list = [newList mutableCopy];
}
}
-(void)updateTitle:(NSString *)newTitle:(NSString *)theIndex
{
int i = [theIndex intValue]-1;
[self.list replaceObjectAtIndex:i withObject:newTitle];
NSLog((NSString *)[self.list objectAtIndex:i]); // gives the correct output
}
Sin embargo, el cambio sigue siendo cierto sólo dentro del método. desde cualquier otro método, el
NSLog((NSString *)[self.list objectAtIndex:i]);
da el mismo valor anterior.
¿Cómo puedo reemplazar el objeto viejo con uno nuevo en un índice específico para que el cambio también se note desde cualquier otro método?
incluso modificó el método como este, pero el resultado es el mismo:
-(void)updateTitle:(NSString *)newTitle:(NSString *)theIndex
{
int i = [theIndex intValue]-1;
NSMutableArray *localList = [[NSMutableArray alloc] init];
localList = [localList mutableCopy];
for(int j = 0; j < [list count]; j++)
{
if(j == i)
{
[localList addObject:newTitle];
NSLog(@"j == 1");
NSLog([NSString stringWithFormat:@"%d", j]);
}
else
{
[localList addObject:(NSString *)[self.list objectAtIndex:j]];
}
}
[self.list release];
//self.list = [localList mutableCopy];
[self setList:localList];
[localList release];
}
por favor ayuda a chicos :)
Lo sentimos, pero que realmente necesita para trabajar a través de la documentación de Objective-C, los documentos de gestión de memoria (que son geniales) y los capítulos de propiedad. Este código * realmente * tiene errores en todas partes ... – Eiko