我正在开发一个CoreData应用程序,该应用程序将志愿者电话号码分配给本周不同的早晨和下午。本周的每一天都有十四个实体,一个上午和一个下午。
但现在我想添加一个我称之为“AllCall”的第十五个实体。我希望任何其他十四个实体中的任何一个都可以自动添加到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
}
}
}
感谢您的帮助!
利
答案 0 :(得分:1)
您是否尝试过将它们全部继承自父对象,该对象具有您希望在其中具有全局属性的任何属性?
答案 1 :(得分:1)
class ParentObject: NSManagedObject {
}
class ChildObject: ParentObject {
}
子对象将继承父级自动拥有的任何属性。您仍然需要设置一个在所有实体中分配的功能。如果适用于所有子项,则为父类提供所有关系信息。然后,当您从反向访问它时,您应该能够遍历每个孩子并设置他们的全局值。如果您不从关系中访问它们,您应该只能从对ParentObject的获取请求中访问它们。