我有一个NSMutableArray
对象(保留,全部合成),它被很好地初始化了,我可以使用addObject:
方法轻松地向其中添加对象。但是,如果我想在特定索引处用新对象替换该NSMutableArray
中的一个对象,则无法实现。
例如:
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
}
然而,这种改变仅在该方法内部有效。从其他任何方法访问时,
NSLog((NSString *)[self.list objectAtIndex:i]);
返回相同的旧值。
我该如何在特定索引处实际替换旧对象为新对象,以便可以从任何其他方法中注意到更改。
我甚至修改了这个方法,但结果仍然是一样的:
-(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];
}
请大家帮个忙 :)