问题描述
||
//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具有两个单独的对象(每个对象分配了单独的内存空间),每个对象都有自己的一组“名称”和“坐标”属性。但是上面的代码显然只是更改了同一对象“ currentPlaces”的属性,并且其引用两次添加到了数组中。暗示我只在内存中分配了一个对象。当我使用快速枚举和NSlog遍历数组时,这两个元素的name属性都会两次出现最后一次设置的值。
采用NScopying协议可以解决问题吗?
[placesMutArray addobject:[currentPlace copy]];
如果是,那我应该怎么做?我尝试过,但是我遇到很多错误。
解决方法
您使用的是同一实例,这是正确的。您只需要制作一个新的。
尝试这个 :
// 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
变量仍指向第一个对象,因此当开始设置新名称和坐标时,您将更新第一个,而不创建新对象。
, 您仅创建了一个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];
无论哪种方式,请记住在使用分配,复制或保留时释放对象
[secondPlace release];