2016-06-23 105 views
2

我正在開發一個CoreData應用程序,該應用程序將志願者電話號碼分配到一週的不同上午和下午。一週中的每一天有一天早上和下午有十四個實體。如何將一個電話號碼添加到多個實體

但是現在我想添加一個我稱之爲「AllCall」的第15個實體。我希望其他14個實體中的任何一個實體都能自動添加到AllCall中。那就是我迷失的地方。我非常感謝指出正確的方向。

我試圖只爲我的新實體的代碼加倍,但沒有奏效。事實上,它阻止了原始代碼的工作。

以下是我有:

進口的UIKit 進口CoreData 進口AVFoundation 進口CloudKit

public var allSelected:Bool = false 
public var phoneList = [String]() 
public var phoneList2 = [String]() 
public var switchStateArray = [String]() 



class TableViewController: UITableViewController { 

var moc:NSManagedObjectContext! 

var firstLaunch = true 

var iCloudIsReady = false 


override func viewDidLoad() { 
    super.viewDidLoad() 


    // SET UP ICLOUD 

    print ("iCloudIsReady starts as \(iCloudIsReady)") 

    self.navigationItem.title = "Waiting for iCloud...l" 

    if self.iCloudIsReady == false { 
    self.navigationItem.title = "Waiting for iCloud...l" 
    self.navigationItem.rightBarButtonItem?.enabled = false 
    self.navigationItem.leftBarButtonItem?.enabled = false 
    self.navigationController!.toolbarHidden = false 

    } 

    else { 

     self.iCloudIsReady = true 
     self.navigationItem.title = SelectedEntity 
     self.navigationItem.rightBarButtonItem?.enabled = true 
     self.navigationItem.leftBarButtonItem?.enabled = true 
     self.navigationController!.toolbarHidden = false 

    } 



} 

// BAR BUTTON OUTLET AND VARIABLES 


@IBOutlet var selectAll: UIBarButtonItem! 

var audioPlayer = AVAudioPlayer() 
var SelectedEntity:String = "" 
var List: Array<AnyObject> = [] 
var numberOfSections:Int = 1 
var theSwitchTag:Int = 0 
var theSwitchState:Bool = false 
var alphaName:String = "" 


override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

// MARK: - Table view data source 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // #warning Incomplete implementation, return the number of sections 
    return 1 
} 



override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    print ("Did numberOfRows") 
    return List.count 
} 





override func viewWillAppear(animated:Bool) { 

    print (phoneList2) 

    print ("View Appeared") 

    phoneList2.removeAll() 

    turnAllOff() 

    allSelected = false 


     self.navigationItem.title = SelectedEntity 
     self.navigationItem.rightBarButtonItem?.enabled = true 
     self.navigationItem.leftBarButtonItem?.enabled = true 
     self.navigationController!.toolbarHidden = false 




    self.tableView.backgroundColor = UIColor.blueColor() 

    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext 


    moc = context 



    let AppDel: AppDelegate? = (UIApplication.sharedApplication().delegate as? AppDelegate)! 

    let Context: NSManagedObjectContext = AppDel!.managedObjectContext 

    let Context2: NSManagedObjectContext = AppDel!.managedObjectContext 

    print ("Called persistentStoreDidChange") 

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TableViewController.persistentStoreDidChange), name: NSPersistentStoreCoordinatorStoresDidChangeNotification,object:nil) 
    NSNotificationCenter.defaultCenter().addObserver(self,selector:Selector("persistentStoreWillChange:"), name: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: moc.persistentStoreCoordinator) 

    print ("Called persistentStoreWillChange") 

    NSNotificationCenter.defaultCenter().addObserver(self,selector:"receiveICloudChanges:", name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: moc.persistentStoreCoordinator) 


    self.loadData() 

} 



override func viewWillDisappear(animated:Bool) { 

    print ("Deactivated these notifications") 

    NSNotificationCenter.defaultCenter().removeObserver(self, name:NSPersistentStoreCoordinatorStoresDidChangeNotification, object:nil) 
    NSNotificationCenter.defaultCenter().removeObserver(self, name: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: moc.persistentStoreCoordinator) 
    NSNotificationCenter.defaultCenter().removeObserver(self, name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: moc.persistentStoreCoordinator) 


    self.turnAllOff() 


    self.moc.reset() 



} 


func persistentStoreDidChange() { 

    print("Called persistenStoreDidChange") 
self.navigationItem.title = (SelectedEntity) 
self.navigationItem.rightBarButtonItem?.enabled = true 
self.navigationItem.leftBarButtonItem?.enabled = true 
    self.iCloudIsReady = true 
    print ("iCloudIsReady is switched to \(iCloudIsReady)") 

    self.loadData() 
    self.tableView.reloadData() 


} 


func persistentStoreWillChange(notification:NSNotification) { 

    self.navigationItem.title = "Changes in progress..." 
    self.navigationItem.rightBarButtonItem?.enabled = false 
    self.navigationItem.leftBarButtonItem?.enabled = false 


    moc.performBlock {() -> Void in 

     if self.moc.hasChanges { 

      let error:NSError? = nil 
      try! self.moc.save() 
      if error != nil { 

       print ("Save error: \(error)") 

      } 

      else { 

       self.moc.reset() 

      } 

     } 



    } 


} 



func receiveICloudChanges (notification:NSNotification) { 

    print ("Received iCloud changes") 

    moc.performBlock {() -> Void in 
     self.moc.mergeChangesFromContextDidSaveNotification(notification) 

     self.loadData() 


    } 

} 

// LOAD DATA FOR SELECTED DAY 

func loadData() { 

    let request = NSFetchRequest(entityName: SelectedEntity) 

    let nameSort = NSSortDescriptor(key: "name", ascending: true) 

    request.sortDescriptors = [nameSort] 


    List = try! moc.executeFetchRequest(request) 


    for var i = 0;i<=(List.count-1);i+=1 {   


     let phoneBook: NSManagedObject = List[i] as! NSManagedObject 

     let additionToList = (phoneBook.valueForKey("phonenumber") as! NSString as String) 


     if phoneList.contains(additionToList) == false { 

      print ("Added") 

      phoneList.append(additionToList) 
      phoneList2.removeAll() 


     } 

    } 


    print ("The current dial list is \(phoneList2)") 


} 



override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 


    print ("I'm doing this") 

    let cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell 

    let data: NSManagedObject = List[indexPath.row] as! NSManagedObject 

    for var x = 0; x <= List.count; x+=1 { 

     switchStateArray.append("OFF") 

    } 

    cell.Name?.text = data.valueForKey("name") as? String 
    alphaName = String(cell.Name?.text) 
    cell.PhoneNumber?.text = data.valueForKey("phonenumber") as? String 
    cell.Group.text = data.valueForKey("group") as? String 
    cell.FirstName.text = data.valueForKey("firstname") as? String 
    cell.mySwitch.tag = indexPath.row 
    theSwitchTag = cell.mySwitch.tag 

    cell.mySwitch.restorationIdentifier = "\(indexPath.row)" 

    let y:Int = indexPath.row 

    print ("My indexPath.row is \(y)") 

    if switchStateArray[y] == "ON" { 

     cell.mySwitch.setOn(true,animated:true) 



     } 


    else if switchStateArray[y] == "OFF"    { 

     //user did turn off individual switch or did Delsect All 

       cell.mySwitch.setOn(false,animated: true) 


      } 

    cell.mySwitch.addTarget(self, action: "switchChanged:", forControlEvents: UIControlEvents.ValueChanged) 

    cell.mySwitch.backgroundColor = UIColor.blueColor() 
    cell.mySwitch.layer.cornerRadius = 16.0; 

    cell.Name.textColor = UIColor.whiteColor() 
    cell.PhoneNumber.textColor = UIColor.whiteColor() 
    cell.Group.textColor = UIColor.whiteColor() 
    cell.FirstName.textColor = UIColor.whiteColor() 


    return cell 


    // Configure the cell... 


} 

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 


} 

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
    // Change the color of all cells 
    cell.backgroundColor = UIColor.blueColor() 


} 


func switchChanged(sender: UISwitch) { 


    let soundPath = NSBundle.mainBundle().pathForResource ("clicksound", ofType: "wav") 
    let soundURL = NSURL.fileURLWithPath(soundPath!) 
    self.audioPlayer = try! AVAudioPlayer (contentsOfURL:soundURL) 
    self.audioPlayer.play() 



    let cell: TableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell 


    let view = sender.superview! 
    let parentCell = view.superview as! TableViewCell 
    let indexPath = tableView.indexPathForCell(parentCell) 
    let intIndexPath = Int(indexPath!.row) 



    if sender.on == true { 


     print ("You just turned on switch number \(sender.tag)") 

     phoneList2.append(phoneList[indexPath!.row]) 


     print ("The value of indexPath is now \(intIndexPath)") 

     switchStateArray[intIndexPath] = "ON" 


     if phoneList2.count == phoneList.count { 

      selectAll.title = "Deselect All" 

     } 


    } 

    else if sender.on == false { 

     print ("You just turned off switch number \(sender.tag)") 


     switchStateArray[intIndexPath] = "OFF" 

     phoneList2 = phoneList2.filter({ $0 != phoneList[intIndexPath] }) 

     print ("I've removed \(phoneList[intIndexPath]) and the list is now \(phoneList2)") 

     if phoneList2.count == 0 { 

      selectAll.title = "Select All" 

     } 


    } 

} 

func turnAllOn() { 


     switchStateArray.removeAll() 
     for var x = 0; x <= List.count; x+=1 { 

      switchStateArray.append("ON") 

      phoneList2 = phoneList 

     } 

    self.tableView.reloadData() 


} 

func turnAllOff() { 


    switchStateArray.removeAll() 

    for var x = 0; x <= List.count; x+=1 { 

     switchStateArray.append("OFF") 

    } 

    self.tableView.reloadData() 


} 

@IBAction func selectAllBtn(sender: UIBarButtonItem) { 


    allSelected = !allSelected 



    if allSelected == true { 

     print ("allSelected is now \(allSelected)") 
     print ("You pressed Select All") 
     selectAll.title = "Deselect All" 
     self.turnAllOn() 

     print ("The dial list is now full: \(phoneList2)") 


    } 

    else { 

     print ("allSelected is now \(allSelected)") 
     selectAll.title = "Select All" 
     print ("You pressed Deslect All") 
     phoneList2.removeAll() 
     self.turnAllOff() 
     print ("The dial list is now empty: \(phoneList2)") 
     self.tableView.reloadData() 



    } 


} 


// Override to support conditional editing of the table view. 
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
    // Return false if you do not want the specified item to be editable. 
    return true 
} 

// Override to support editing the table view. 
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 

    let AppDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 

    let Context: NSManagedObjectContext = AppDel.managedObjectContext 

    if editingStyle == UITableViewCellEditingStyle.Delete { 

     print("Before deletion, phoneList2 is \(phoneList2)") 

     phoneList2 = phoneList2.filter({ $0 != phoneList[indexPath.row] }) 

     print ("I excluded \(phoneList[indexPath.row])") 


     Context.deleteObject(List[indexPath.row] as! NSManagedObject) 


     List.removeAtIndex(indexPath.row) 


     print ("That name was deleted and the list is now \(phoneList2)") 

     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
     tableView.reloadData() 


    } 

    var error: NSError? = nil 

    do { 

     try Context.save() 
    } 

    catch let error1 as NSError { 

     error = error1 
     print (error) 

    } 

     } 


/* 
// Override to support rearranging the table view. 
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { 

} 
*/ 

/* 
// Override to support conditional rearranging of the table view. 
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
    // Return false if you do not want the item to be re-orderable. 
    return true 
} 
*/ 

    // MARK: - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 

    if segue.identifier == "goBack" { 

     self.turnAllOff() 
     selectAll.title = "Select All" 
     phoneList2.removeAll() 

    } 

    else if segue.identifier == "Compose" { 

     print ("Compose pressed") 

     self.turnAllOff() 
     selectAll.title = "Select All" 


    } 


    if segue.identifier == "editRow" { 


     print (segue.identifier) 

     let indexPath = self.tableView.indexPathForSelectedRow! 

     let selectedItem: NSManagedObject = List[tableView.indexPathForSelectedRow!.row] as! NSManagedObject 

     let ViewCon = segue.destinationViewController as! AddViewController 


     ViewCon.congName = selectedItem.valueForKey("name") as! String 
     ViewCon.congNumber = selectedItem.valueForKey("phonenumber") as! String 
     ViewCon.congGroup = selectedItem.valueForKey("group") as! String 
     ViewCon.congFirst = selectedItem.valueForKey("firstname") as! String 
     ViewCon.SelectedDay = SelectedEntity 


     ViewCon.existingItem = selectedItem 


    } 


    else if segue.identifier == "addRow" { 

     print ("I'm here") 
     let ViewCon = segue.destinationViewController as! AddViewController 
     ViewCon.SelectedDay = SelectedEntity 

    } 



} 


} 

謝謝您的幫助!

回答

1

您是否嘗試過把他們都從有你想成爲它的內部全局的任何屬性父對象繼承?

+0

聽起來不錯,但我不知道如何在覈心數據中做到這一點。 – user3140521

1
class ParentObject: NSManagedObject { 
} 

class ChildObject: ParentObject { 
} 

子對象將繼承其父項自動擁有的任何屬性。你仍然需要設置一個分類函數來分配所有的實體。如果它適用於所有的孩子,則向父類提供所有的關係信息。然後,當你從它的反向訪問它時,你應該能夠遍歷它的每個孩子並設置它們的全局值。如果你不從一個關係訪問它們,你應該只能從一個獲取請求到ParentObject訪問它們。

相關問題