Frage

In my app I created a bunch of object classes for data that I save in NSUserDefaults.

I get the item by:

LauncherToDoItem *item = [[ActionHelper sharedInstance] actionList][indexPath.row];

then i pass it on to a editing view controller:

LauncherEditActionViewController *editActions = [[LauncherEditActionViewController alloc] initWithToDoItem:item];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:editActions];
    [self presentViewController:navController animated:YES completion:nil];

In the view controller I have a table that shows data from a editing version of the item.

- (id)initWithToDoItem:(LauncherToDoItem *)toDoItem {
    self=[super initWithStyle:UITableViewStyleGrouped];
    if (self) {
        item = toDoItem;
        editedToDoItem = toDoItem;
    }
    return self;
}

When I edit the editedToDoItem it also writes the the item, so I assume it's also writing to the version in the array? Why is it that by editing 1 of them affect it all? I dont save it back to the array yet but values save automatically.

War es hilfreich?

Lösung

That's because both item and editedToDoItem point to the same object — and the same exact location in memory. When you write item = toDoItem, what you're really doing is saving the pointer to toDoItem inside the variable item. It's a reference to the original object, not a copy, because Objective-C object variables are pointers to the objects in memory.


Consider the following code:

NSMutableString *string = [@"Hello, world!" mutableCopy];
NSMutableString *a = string;
NSMutableString *b = string;

// string, a, and b point to the same exact object.
[string appendString:@" Hi again!"];
NSLog(@"%@", a); // => "Hello, world! Hi again!"
[b appendString:@" Whoa!"];
NSLog(@"%@", a); // => "Hello, world! Hi again! Whoa!"

When you fetch the item from your array, then store it twice in the editing controller, you're just passing around references to the same object, which, when edited, will reflect on all other references that you have — because they point to the same location in memory.

If you really want several different copies of the object (so that editing one doesn't affect the others), you have to actually copy the objects by making them conform to the NSCopying Protocol and using [item copy].

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top