代码之家  ›  专栏  ›  技术社区  ›  Michael

nsmanagedObject setValue问题(核心数据)

  •  3
  • Michael  · 技术社区  · 15 年前

    我希望编辑核心数据中的现有记录。目前,我有这个代码,但它创建了一个新记录(并将正确的数据插入正确的列中):

    NSManagedObjectContext *context = [[NSApp delegate] managedObjectContext];
    NSManagedObject *instrument  = nil;
    
    
    
    instrument = [NSEntityDescription insertNewObjectForEntityForName: @"Instrument"
                      inManagedObjectContext: context];
    
    [instrument setValue:[NSNumber numberWithInt:quantityInStockInstruments] 
        forKey: @"quantity"];
    

    结果如下:

    Instrument | Value | Quantity
    
    Violin     | £25   | 9
    
               |       | 8 <<< This is the new record that is created, instead of setting the
                               quantity of violin from '9' to '8'
    

    我希望程序编辑当前突出显示的行(在本例中是“小提琴”行)的数量列。我该怎么做?

    2 回复  |  直到 14 年前
        1
  •  4
  •   Abizern    15 年前

    正如Reuggentis所说,线索在选择器的名字中。您正在添加新对象。

    更好的方法是使用 selectedObjects 你的NSarraycontroller。举个例子(为了清晰起见,这是长篇大论,我把它写在了头顶上):

    // Get the selected objects from the NSArrayController.
    // There may be more than one object selected, so this needs to be accounted for.
    NSArray *selectedObjectsArray = [yourArrayController selectedObjects];
    
    // Get the first object in the array, this is the one that will have it's values changed.
    id firstSelectedObject = [selectedObjectsArray objectAtIndex:0];
    
    // Change a value in a KVC compliant way
    [firstSelectedObject setValue:newValue forKey:@"keyValueToChange"];
    

    编辑后添加评论

    您是否有一个到阵列控制器的插座并在Interface Builder中正确连接?

    不管怎样,代码对我有效。这里是一个安 example project 显示它工作。

        2
  •  1
  •   refulgentis    15 年前

    注意选择器名称:“insert 新的 对象:InContext”。

    正如Amrox所说,这取决于您的模型(即核心数据)和控制器的连接方式。我很难在不了解你的代码的情况下说出来,特别是因为我通常更喜欢iPhone方面的东西(它没有绑定),但基本上你需要说[[yourdataarray objectatindex:[table selectedrow]]setvalue:@“whatever”forkey:@“whatever”]

    推荐文章