請糾正我,我錯了(我是一個begginer) 我想存儲一個類對象到NSArray中。例如:將對象存儲到NSMutableArray
MySimpleClass *mscObj = [[MySimpleClass alloc] initWithSomething:@"something"];
NSMutableArray *myarr = [[NSMutableArray alloc] init];
[myarr addObject:mscObj];
mscObj = @"somethingelse";
然後我的myarr索引0從@「something」變成@「somethingelse」。爲什麼?我可以僅將副本存儲到數組中嗎?
編輯: 在MySimpleClass:
#import <Foundation/Foundation.h>
@interface MySimpleClass : NSObject {
}
@property (strong,nonatomic) NSString *objectName;
@property (strong,nonatomic) NSString *objectTarget;
-(void)addName:(NSString*)name;
-(void)addTarget:(NSString*)target;
@end
.m文件
#import "MySimpleClass.h"
@implementation MySimpleClass
@synthesize objectName;
@synthesize objectTarget;
-(void)addName:(NSString*)name{
self.objectName = name;
}
-(void)addTarget:(NSString*)target{
self.objectTarget = target;
}
-(void)flushAll {
self.objectTarget = nil;
self.objectName = nil;
}
@end
在其它類的,我有:
MySimpleClass *mscObj = [[MySimpleClass alloc] initWithSomething:@"something"];
[myarr addObject:[mscObj copy]];
int testunit = [myarr count];
for(int i=0;i<testunit;i++) {
MySimpleClass *myelement = [myarr objectAtIndex:i];
NSLog(@"%@ : %@",myelement.objectName,myelement.objectTarget);
}
你改變了mscObj和NSArray的值只存儲對象的refence。你的myarr索引0指的是對象值已被改變的同一個對象。如果你想在0的索引應該有「東西」,並在1索引它應該是「somethingelse」,那麼你必須保持索引0的對象的副本,然後通過使用addObject:方法添加更新的副本mscObj索引1 – dayitv89 2012-04-17 13:16:30