![](/img/trans.png)
[英]unrecognized selector sent to instance while trying to add an object to a mutable array
[英]How can i add new object instance in a mutable array using same object reference as the previous one
//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]];
如果是,那我应该怎么做? 我尝试过,但是我遇到很多错误。
您仅创建了一个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,复制或保留时释放对象
[secondPlace release];
您使用的是同一个实例,这是正确的。 您只需要制作一个新的。
尝试这个 :
// 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
变量仍指向第一个对象,因此当开始设置新名称和坐标时,您将更新第一个对象,而不创建新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.