开发者

How do I change a value for a key at a specific index?

I have been stuck trying to figure out how to change a value for a key at a specific index. For example if I have the following data,

Index |  slideNumber  |  Title
--------------------------------------------
1     |      5        |  test 1
2     |      2        |  test 2
3     |      5        |  test 3
4     |      7        |  test 4
5     |      9        |  test 5

If I want to change the value of slideNumber at index 3, how wo开发者_运维技巧uld I do that? Thank you in advance!


Assuming that your Core Data Entity has three attributes: index, slideNumber, title

You can retrieve the correct entity (an instance of a row in that table if you are thinking like a database which I recommend against) with the following code:

NSManagedObjectContext *moc = ...;
NSInteger myIndex = 3;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"index == %i", myIndex]];

NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
if (error && !results) {
  NSLog(@"Error %@\n%@", [error localizedDescription], [error userInfo]);
}
NSManagedObject *myEntity = [results lastObject];

Now that we have the entity, editing a value is a simple KVC call away:

[myEntity setValue:[NSNumber numberWithInteger:5 forKey:@"slideNumber"];

From there, you will probably want to save your changes:

NSManagedObjectContext *moc = ...;
NSError *error = nil;
if (![moc save:&error]) {
  NSLog(@"Error %@\n%@", [error localizedDescription], [error userInfo]);
}

It is best to think of Core Data as an object graph and NOT as a table in a database. The database is just a means to persist the data.

I also recommend reading up on KVC (Key Value Coding). You can avoid using KVC if you want by subclassing your NSManagedObjects but it is unnecessary.


Edit (thanks for the suggestion @morningstar):

This would probably be a quicker way to do it:

- (void)newSlideNumber:(NSInteger)slideNumber 
              forIndex:(NSInteger)index {
    NSError *error = NULL;
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Slides" 
                                   inManagedObjectContext:self.managedObjectContext]];

    [request setPredicate:[NSPredicate predicateWithFormat:@"Index == %d", index]];
    NSArray *results = [self.managedObjectContext executeFetchRequest:request 
                                                                error:&error];

    [request release];
    if ([results count]) {
        [(NSManagedObject *)[results objectAtIndex:0] setValue:[NSNumber numberWithInteger:slideNumber] 
                                                        forKey:@"slideNumber"];
    } else if (error) {
        NSLog(@"%@", [error description]);
    } else {
        NSLog(@"predicateWithFormat (Index == %d) did not match any objects!", index);
    }
}

Orig

Are you doing this with CoreData? If so, here is a guide (untested and probably wont work exactly as it is if copy/pasted. Just to be used as an example):

- (void)newSlideNumber:(NSInteger)slideNumber forIndex:(NSInteger)index withTitle:(NSString *)title {
    NSError *error = NULL;
    // Delete the objects first, then recreate them:
    [self deleteObjectsForEntityNamewithPred:@"MyEntityName" withPredicate:[NSPredicate predicateWithFormat:@"Index == %d", index]]; // This method is the one defined below

    // Get the managed object from your context:
    NSManagedObject *managedObjectStore = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntityName" inManagedObjectContext:self.managedObjectContext];

    // Set the new values:
    [managedObjectStore setValue:[NSNumber numberWithInteger:index] forKey:@"Index"];
    [managedObjectStore setValue:[NSNumber numberWithInteger:slideNumber] forKey:@"slideNumber"];
    [managedObjectStore setValue:title forKey:@"Title"];

    // Save the context
    [self.managedObjectContext save:&error];
    if (error) {
        NSLog(@"%@", [error description]);
    }
}


- (void)deleteObjectsForEntityNamewithPred:(NSString *)entityName withPredicate:(NSPredicate *)pred {
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    [request setPredicate:pred];
    NSError *error = NULL;
    NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
    [request release];
    if (error) {
            NSLog(@"%@", [error description]);
    }
    for (NSManagedObject *managedObject in results) {
        [self.managedObjectContext deleteObject:managedObject];
    }
}

Some Reference Docs:

NSPersistentStoreCoordinator Class Reference

NSManagedObjectContext Class Reference

NSManagedObjectModel Class Reference


0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜