请纠正我,我错了(我是初学者)我想将一个类对象存储到 NSArray 中。例如:
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);
}