2015-07-07 1 views
0

Я пытаюсь использовать чужой код в качестве основы для того, что я хочу делать. Однако, похоже, он написан для более старой версии Swift, и поэтому я получаю много ошибок. Я смог исправить немало, но теперь я в тупике.Попытка конвертировать старый код Swift - Cstring issue

код Я исправляя это:

import UIKit 

class ViewController: UIViewController { 

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
var array_data: NSMutableArray = [] 

@IBOutlet var table_data : UITableView? 
override func viewDidLoad() { 
    super.viewDidLoad() 
    selectFunc() 

    self.navigationItem.title="Empolyee List" 
    var addBtn = UIBarButtonItem(title: "Add", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("insertFunc")) 
    self.navigationItem.rightBarButtonItem = addBtn 


} 
override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 
    selectFunc() 
} 


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

// I did some work on the block below to get rid of the use of Cstring (Deprecated) that has caused issues below 

func selectFunc(){ 
    var selectQuery="select * from EmployeInfo" 
    var result:CInt=0 

    var stmt:COpaquePointer = nil 
    result = sqlite3_prepare_v2(appDelegate.database, selectQuery, -1, &stmt, nil); 
    if result != SQLITE_OK 
    { 
     println("failed \(sqlite3_errmsg(appDelegate.database))") 
    } 
    else 
    { 
     result = sqlite3_step(stmt) 
     array_data.removeAllObjects() 
     while result == SQLITE_ROW { 
      var Dictionary = NSMutableDictionary() 

      let name = sqlite3_column_text(stmt, 0) 
      let dep = sqlite3_column_text(stmt, 1) 
      let sal = sqlite3_column_text(stmt, 2) 

// This is where the errors start - next three lines 


      Dictionary.setObject(String.fromCString(CString(name)), forKey:"name") 
      Dictionary.setObject(String.fromCString(CString(dep)), forKey: "department") 
      Dictionary.setObject(String.fromCString(CString(sal)), forKey: "salary") 

// The error (not surprisingly) is "Use of Unresolved identifier 'Cstring'" 


//OK for those who run into this issue... 

//use...     Dictionary.setObject(String.fromCString(UnsafePointer<CChar>(name))!, forKey: "name") 
      Dictionary.setObject(String.fromCString(UnsafePointer<CChar>(dep))!, forKey: "department") 
      Dictionary.setObject(String.fromCString(UnsafePointer<CChar>(sal))!, forKey: "salary") 


      array_data .addObject(Dictionary) 
      result = sqlite3_step(stmt) 

     } 
    } 
    self.table_data!.reloadData() 
} 
func insertFunc(){ 

    let vc : UIViewController = storyboard!.instantiateViewControllerWithIdentifier("AddViewController") as! UIViewController; 
    self.navigationController!.pushViewController(vc, animated: true) 
} 


func numberOfSectionsInTableView(tableView: UITableView!) -> Int { 
    return 1 
} 

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { 
    return self.array_data.count 
} 

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { 
    //simple cell 
    var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell 
    if !(cell != nil) { 
     cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL") 
    } 
    var dic=array_data.objectAtIndex(indexPath.row) as! NSDictionary 
    cell!.textLabel!.text = dic.valueForKey("name") as! String 
    return cell 
} 
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){ 
    let vc = storyboard!.instantiateViewControllerWithIdentifier("update_deleteViewController") as update_deleteViewController; 
    vc.dictionary=array_data.objectAtIndex(indexPath.row) as NSDictionary 
    self.navigationController.pushViewController(vc, animated: true) 
} 

} 

Есть и другие вопросы в рамках проекта, но это даст мне хороший старт.

+2

Пожалуйста уменьшить свой код на ту часть, которая на самом деле вызывают проблемы, а также добавлять точные сообщения об ошибках. –

+0

Возможно, это то, что вы ищете http://stackoverflow.com/a/25169265/1187415? –

+0

Я ввел данные выше – IanMac

ответ

0

Извлечение данных из SQLite базы данных, используя язык программирования Свифта

Func retrivingDataFromSqliteDb() {

var database:COpaquePointer = nil 

    // This is for getting document directory path or database path 
    let dbpath = appDelegate.getting_SandBox_Path().cStringUsingEncoding(NSUTF8StringEncoding) 

    // open the database and checking open or not 
    let error = sqlite3_open(dbpath, &database) 

    if error != SQLITE_OK { 

     println("Error while opening"); 
    } 
    else{ 
     println("already database open"); 


     var selectQuery = "select * from emptab" 

     var result:CInt = 0 
     var stmt:COpaquePointer = nil 

     result = sqlite3_prepare_v2(database, selectQuery, -1, &stmt, nil); 
     if result != SQLITE_OK { 

      println("failed : \(sqlite3_errmsg(database))") 
     } 
     else { 

      result = sqlite3_step(stmt) 
      array_data.removeAllObjects() 

      while result == SQLITE_ROW { 
      var Dictionary = NSMutableDictionary() 

      let fname = sqlite3_column_text(stmt, 0) 
      let lname = sqlite3_column_text(stmt, 1) 
      let phone = sqlite3_column_text(stmt, 2) 
      let email = sqlite3_column_text(stmt, 3) 
      let address = sqlite3_column_text(stmt, 4) 

     // adding to retrived objects to dictionary 
    Dictionary.setObject(String.fromCString(UnsafePointer<CChar>(fname))!, forKey: "firstName") 
    Dictionary.setObject(String.fromCString(UnsafePointer<CChar>(lname))!, forKey: "LastName") 
    Dictionary.setObject(String.fromCString(UnsafePointer<CChar>(phone))!, forKey: "MobileNum") 
    Dictionary.setObject(String.fromCString(UnsafePointer<CChar>(email))!, forKey: "mail") 
    Dictionary.setObject(String.fromCString(UnsafePointer<CChar>(address))!, forKey: "address") 


       // dictionary of data adding to the Array 
       array_data .addObject(Dictionary) 

       result = sqlite3_step(stmt) 

      } 
      println(array_data) 

     } 

    } 

} 
+0

его работа для меня хорошая – jemeeluNaidu

Смежные вопросы