來替換對象在一個NSMutableArray有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文檔,內存管理文件(很棒)和屬性章節。這個代碼*真的*是越野車... – Eiko 2010-06-17 19:41:55