//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
output i get :
Name is : def
Name is : def
desired output :
Name is : abc
Name is : def
I want the placesMutArray to have two separate objects (each allocated separate memory space) each with their own set of "name" and "coordinates" property. But the above code, apparently, just changes the property of same object 'currentPlaces' and its reference gets added to the array twice. Implying i only get one object allocated in memory. When i traverse the array using fast enumeration and NSlog the name property for both elements i jut get last set value twice.
Can adopting NSCopying protocol solve the problem?
[placesMutArray addObject:[currentPlace copy]];
If yes, then how should i go about it? I tried but i am getting lot of errors.