0

我的代码设置了它的实体、上下文等,然后保存了一条记录,一切正常。然后我想保存一条新记录,但代码会覆盖原始记录。

如何在同一个实例中编写多个项目?

AppDelegate *appdelagate = [[UIApplication sharedApplication]delegate];
context = [appdelagate managedObjectContext];
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"UserData" inManagedObjectContext:context];
NSManagedObject *userData = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];
            [userData setValue:@"Bob" forKey:@"userCD"];
            [userData setValue:@"Tall" forKey:@"dataCD"];
            // Store in the DB
            [context save:&error];

一些如何移动到下一个记录

    [userData setValue:@"John" forKey:@"userCD"];
    [userData setValue:@"Short" forKey:@"dataCD"];
    // Store in the DB
    [context save:&error];

我想我需要释放 userData 并再次声明......我还认为我错过了很多东西,应该停止思考 SQL。

谢谢

4

1 回答 1

2

那是因为您更改了第一个userData对象的属性,而不是创建一个新对象:

NSManagedObject *userData;
// Create first object:
userData = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];
[userData setValue:@"Bob" forKey:@"userCD"];
[userData setValue:@"Tall" forKey:@"dataCD"];
[context save:&error];
// [userData release];  only if you don't compile with ARC

// Create second object:
userData = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];
[userData setValue:@"John" forKey:@"userCD"];
[userData setValue:@"Short" forKey:@"dataCD"];
[context save:&error];
// [userData release];  only if you don't compile with ARC
于 2013-04-24T14:02:25.937 回答