我正在开发一个 CoreData 应用程序,该应用程序可以将志愿者电话号码分配给一周中的不同上午和下午。有十四个实体,一周中的每一天一个上午和一个下午。
但现在我想添加第十五个实体,我称之为“AllCall”。我希望其他 14 个实体中的任何一个的任何条目都自动添加到 AllCall。那就是我迷路的地方。如果有人指出正确的方向,我将不胜感激。
我试图为新实体加倍我的代码,但那没有用。事实上,它被原始代码阻止了工作。
这是我的:
导入 UIKit 导入核心数据 导入 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
}
}
}
感谢您的帮助!
伊莱
最佳答案
您是否尝试过让它们都继承自一个父对象,该对象具有您希望在其中成为全局属性的任何属性?
关于swift - 如何将一个电话号码添加到多个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37999311/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack