Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can i add new object instance in a mutable array using same object reference as the previous one
    text
    copied!<pre><code>//viewController.h file //--------------------- #import &lt;UIKit/UIKit.h&gt; @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 </code></pre> <p>output i get :</p> <pre><code>Name is : def Name is : def </code></pre> <p>desired output :</p> <pre><code>Name is : abc Name is : def </code></pre> <p>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.</p> <p>Can adopting NSCopying protocol solve the problem? </p> <pre><code>[placesMutArray addObject:[currentPlace copy]]; </code></pre> <p>If yes, then how should i go about it? I tried but i am getting lot of errors.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload