Swift2中的coreData - 更新条目

时间:2015-08-26 14:12:48

标签: ios swift core-data

在objC我曾经这样做过:

.h文件

@class Foo

@interface ViewController {
@private
Foo *foo;

  ...

}

@property (nonatomic, strong) Foo * foo;

.m文件

#import "Foo.h" 

@implementation ViewController
@synthesize foo;

然后我能够做到这一点:

- (void)buttonTapped:(id)sender{

    NSString *value = @"ON";
    NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
    UIImage *unselectedImage = [UIImage imageNamed: @"foo.png"];
    UIImage *selectedImage = [UIImage imageNamed:@"doo.png"];

    if ([sender isSelected]) {
        [sender setImage:unselectedImage forState:UIControlStateNormal];
        [sender setSelected:NO];
        value = @"OFF";
        [userPreferences setObject:value forKey:@"stateOfButton"];

        foo.attribute = nil;


    }else {
        [sender setImage:selectedImage forState:UIControlStateSelected];
        [sender setSelected:YES];
        value = @"ON";
        [userPreferences setObject:value forKey:@"stateOfButton"];



         foo.attribute = @"someString";

    }

    NSManagedObjectContext *context = xray.managedObjectContext;
    NSError *error = nil;
    if (![context save:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    [userPreferences synchronize];

}

如果有人用swift2做同样的事情? 从昨天起,它一直困扰着我。它真的不应该那么难。应该吗?

编辑:

许多尝试失败之一:

var foo : Foo = Foo()

  @IBAction func buttonTapped(sender: UIButton) {


      let foo = NSEntityDescription.insertNewObjectForEntityForName("EntityName", inManagedObjectContext: self.managedObjectContext!) as! Foo 
// if you comment this you get this error: fatal error: unexpectedly found nil while unwrapping an Optional value

        var value: NSString = "ON"
        let userPrefs: NSUserDefaults = NSUserDefaults()
        let unselectedImage = UIImage(named:"foo.png")
        let selectedImage = UIImage(named: "doo.png")



        if sender.selected {
            sender .setImage(unselectedImage, forState: .Normal)
            sender.selected = false
            value = "OFF"
            userPrefs.setObject(value, forKey: "stateOfButton")



            foo.attribute = nil
        }

        else {

            sender .setImage(selectedImage, forState: .Normal)
            sender.selected = true
            value = "ON"
            userPrefs.setObject(value, forKey: "stateOfButton")



           foo.attribute = "someString"
        }

         let context = foo.managedObjectContext

    do {
            try context!.save()
            } catch {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            //print("Unresolved error \(error), \(error.userInfo)")
            abort()
            }

        userPrefs.synchronize()

    }

这给了我一个错误:

An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:.  Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (6), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

1 个答案:

答案 0 :(得分:0)

这似乎成了诀窍:

 self.detailItem?.attribute = "someString"

其中detailedItem

  var detailItem: Foo? 

var foo: Foo = Foo()

准备segue功能:

 var foo: Foo!
             foo = filteredObjects![indexPath.row] as Foo
                let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
                controller.detailItem = foo