//viewController.h file
//---------------------
#import <UIKit/UIKit.h>
@interface ItemClass : NSObject
{
NSString* name;
}
@property (nonatomic, retain) NSString* name;
@end
@interface PlaceClass : ItemClass
{
NSString* coordinates;
}
@property (nonatomic, retain) NSString* coordinates;
@end
@interface viewController : UIViewController {
NSMutableArray* placesMutArray;
PlaceClass* currentPlace;
}
@end
//viewController.m file
//------------------------
#import "viewController.h"
@implementation ItemClass
@synthesize name;
@end
@implementation PlaceClass
@synthesize coordinates;
@end
@implementation viewController
- (void)viewDidLoad {
[super viewDidLoad];
placesMutArray = [[NSMutableArray alloc] init];
currentPlace = [[PlaceClass alloc] init];
// at some point in code the properties of currentPlace are set
currentPlace.name = [NSString stringWithFormat:@"abc"];
currentPlace.coordinates = [NSString stringWithFormat:@"45.25,24.22"];
// currentPlace added to mutable array
[placesMutArray addObject:currentPlace];
//now the properties of currentPlace are changed
currentPlace.name = [NSString stringWithFormat:@"def"];
currentPlace.coordinates = [NSString stringWithFormat:@"45.48,75.25"];
// again currentPlace added to mutable array
[placesMutArray addObject:currentPlace];
for(PlaceClass* x in placesMutArray)
{
NSLog(@"Name is : %@", x.name);
}
}
@end
输出我得到:
Name is : def
Name is : def
期望的输出:
Name is : abc
Name is : def
我希望placesMutArray有两个独立的对象(每个对象分配不同的内存空间),每个对象都有自己的“name”和“coordinates”属性。但是上面的代码显然只是改变了同一个对象'currentPlaces'的属性,并且它的引用被添加到数组中两次。暗示我只在内存中分配了一个对象。当我使用快速枚举和NSlog遍历数组时,两个元素的name属性我将获得两次最后设置值。
可以采用NSCopying协议解决问题吗?
[placesMutArray addObject:[currentPlace copy]];
如果是,那我该怎么办呢?我尝试了但是我遇到了很多错误。
答案 0 :(得分:0)
您只创建了一个PlaceClass对象(currentPlace),然后向该数组添加了对此PlaceClass对象的2个引用。您必须创建第二个对象
secondPlace = [[PlaceClass alloc] init];
secondPlace.name = [NSString stringWithFormat:@"def"];
secondPlace.coordinates = [NSString stringWithFormat:@"45.48,75.25"];
[placesMutArray addObject:secondPlace];
或
secondPlace = [currentPlace mutableCopy];
secondPlace.name = [NSString stringWithFormat:@"def"];
secondPlace.coordinates = [NSString stringWithFormat:@"45.48,75.25"];
[placesMutArray addObject:secondPlace];
无论哪种方式,记得在使用alloc,copy或retain
时释放对象[secondPlace release];
答案 1 :(得分:0)
你是对的,因为你正在使用相同的实例。你只需要制作一个新的。
试试这个:
// Create a second PlaceClass before setting it's properties to 'def'
currentPlace = [[PlaceClass alloc] init];
currentPlace.name = [NSString stringWithFormat:@"def"];
currentPlace.coordinates = [NSString stringWithFormat:@"45.48,75.25"];
将对象添加到数组不会为您复制对象 - 它只是意味着数组知道对象。将第一个currentPlace添加到数组后,currentPlace
变量仍然指向第一个对象,因此在开始设置新名称和坐标时,您正在更新第一个,而不是创建新的。