//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
Я хочу, чтобы placeMutArray имел два отдельных объекта (каждый выделил отдельное пространство памяти) каждый со своимисобственный набор свойств "имя" и "координаты".Но приведенный выше код, по-видимому, просто меняет свойство одного и того же объекта currentPlaces, и его ссылка добавляется в массив дважды.Подразумевается, что я только один объект выделен в памяти.Когда я пересекаю массив, используя быстрое перечисление и NSlog, свойство name для обоих элементов я просто получаю последнее заданное значение дважды.
Может ли принятие протокола NSCopying решить проблему?
[placesMutArray addObject:[currentPlace copy]];
Если да, то как мне это сделать?Я пытался, но получаю много ошибок.