2012-08-08 31 views
0
  1. 我有UITableView
  2. 在所有單元中都有一個UISwitch。
  3. 我的核心數據是由值填充。
  4. 具有@「OFF」值的名爲switchValue的核心數據屬性之一。

現在我需要:如何更改核心數據中的記錄值

  1. 如果用戶設定的UISwitch爲ON。
  2. 該操作會將該行的switchValue屬性的值更改爲@「ON」。

我簡單的代碼是:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 


    NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
    cell.textLabel.text = [[object valueForKey:@"courseCode"] description]; 
    cell.detailTextLabel.text = [[object valueForKey:@"courseName"] description]; 
UISwitch *theSwitch = [[UISwitch alloc]init]; 

    cell.accessoryView = theSwitch; 

    NSLog(@"%@",[[object valueForKey:@"switchValue"] description]); 

    if ([[[object valueForKey:@"switchValue"] description]isEqualToString: @"ON"]) { 

     theSwitch.on = YES; 

    }else{ 

     theSwitch.on = NO; 

    } 


    [theSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged]; 

    return cell; 

} 

和動作是:

-(void) switchChanged: (UISwitch *) sender{ 


    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; 
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity]; 

    if (sender.on) { 

     How can I change the value? 

    }else{ 

    } 

} 

回答

1

一旦你的管理對象,只需將其值設置。

NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
[object setValue:@"ON" forKey:@"switchValue"]; 

如果您希望將這些更改保存到磁盤,您必須在某個時刻保存您的託管對象上下文。

+0

設置他們,但我必須這樣做,如果用戶改變UISwitch上。 – NamshanNet 2012-08-08 21:27:00

+0

我不確定你在問什麼。 – 2012-08-08 22:54:50

1

您應該使用Core Data模型管理器的代碼生成工具(創建模型的圖形)。

但是,您可以隨時獲取值:

[object valueForKey:@"foo"] 

[object setValue:value forKey:@"foo"]; 
+0

感謝您的幫助 – NamshanNet 2012-08-08 21:28:13