【发布时间】:2011-03-05 02:17:10
【问题描述】:
我有一个 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];
}
请大家帮忙:)
【问题讨论】:
-
抱歉,您确实需要阅读 Objective-C 文档、内存管理论文(非常棒)和属性章节。这段代码真的到处都是错误的......
标签: ios objective-c nsarray