Sandeep Sandeep - 1 year ago 79
Objective-C Question

NSMutableArray changing old stored data issue

I am parsing JSON and storing that data into

on my homepage. I want to access that data on my other page not after the another, so I am using Singleton Pattern for sharing common data in my homepage. I am storing that NSMutableArray data to Singleton file for common access. In second page i am showing that data in
. There is one button which modifies the data but will not change original data i.e homepage
. So I am storing that data into
and updating that
. But when I return back to homepage and in
after placing breakpoint I am observing my original data is changed.

Please have a look on this issue and correct me where I am doing wrong with my code.

For more reference I added the project link please download and check this: [Project Link][1]

In this project I have created the 2 View Controllers , 1 model class, and one Singleton for common data across all file.

View Controller:

In this file I am parsing JSON and storing in NSMutableArray and also setting the same array data to Singleton file array for common access across all file.


In this file I am getting array data from Singleton file and storing in local array.

There is one button to modify data. In modify data function I am modifying the data and storing in the other array for common access (

But when I return back to First View Controller and in
after placing breakpoint, I am observing my original data is changed.
Please check, I don't want my original data to be changed. Please check and suggest me where I am doing wrong with my code.

Answer Source

Your problem because all your property( ViewController->shippingArray, SecondPageController->myshippingarray, PersonDtklSingleton->shippingAddress) point to same array.

You can fix problem by clone array with Deep Copies, to copy original to new array. Make sure all items in original array adopted NSCopying.


@implementation SecondPageController
- (void)viewDidLoad {
    [super viewDidLoad];

    myshippingarray=[[NSMutableArray alloc]init];

    // deep copy
    self.myshippingarray = [[NSMutableArray alloc] initWithArray:[[PersonDtklSingleton sharedInstance]shippingAddress] copyItems:YES];
    // Do any additional setup after loading the view.


@implementation PersonModel
@synthesize housernumber,resident,street,city,pincode,defaultAddress;

- (id)copyWithZone:(NSZone *)zone {
    PersonModel *copyObj = [PersonModel new];
    copyObj.housernumber = [self.housernumber copyWithZone:zone];
    copyObj.resident = [self.resident copyWithZone:zone];
    copyObj.street = [self.street copyWithZone:zone]; = [ copyWithZone:zone];
    copyObj.pincode = [self.pincode copyWithZone:zone];
    copyObj.defaultAddress = [self.defaultAddress copyWithZone:zone];
    return copyObj;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download