如何将NSString作为INTEGER存储到数据库?

时间:2014-01-07 09:43:24

标签: ios iphone objective-c sqlite fmdb

如何将NSString存储为Database INTEGER

更新数据库时,应用程序获取Abend。

①用户通过UITextFieldUIPickerView[1~10] * numTextField输入一个数字 ②通过方法numTextField.textintValue转换为int num_int ③将num存储到DB
④通过方法NSString将book.num转换为stringValue * num_text ⑤输出num_text到numTextFieldcell.label3.text

我有这段代码。

图书班操作DB。

Book.m

#define SQL_INSERT @"INSERT INTO books1 (day, title, time, num) VALUES (?, ?, ?, ?);"

- (Book*)add:(Book *)book{
 FMDatabase* db = [self getConnection];
 [db open];
 [db setShouldCacheStatements:YES];

 if( [db executeUpdate:SQL_INSERT, book.day, book.title, book.time, book.num] {
  book.bookId = [db lastInsertRowId];
  }

 else {
  book = nil;
 }

 [db close];

 return book;
}

EditViewController.m

-(void)viewDidLoad{
 if( self.book )
    {
        _titleTextField.text = self.book.title;
        _dayTextField.text = self.book.day;
        _timeTextField.text = self.book.time;

        int num_int = book.num;
        NSNumber *num_n = [[NSNumber alloc] initWithInt:num_int];
        NSString *num_text = [num_n stringValue];
        cell.label3.text = num_text;
    }
 }

- (IBAction)saveData:(id)sender
{    
    Book* newBook = [[Book alloc] init];
    newBook.bookId    = self.book.bookId;
    newBook.title     = _titleTextField.text;
    newBook.day    = _dayTextField.text;
    newBook.time    = _timeTextField.text;

    NSString *num_text = _numTextField.text;
    int num_int = [num_text intValue];
    newBook.num = num_int;

if( self.book ){
  [self.delegate editBookDidFinish:self.book newBook:newBook];
 }
else{
  [self.delegate addBookDidFinish:newBook];
 }
}

TableViewController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Book* book = [self bookAtIndexPath:indexPath];
    cell.label1.text = book.title;
    cell.label2.text = book.time;

    int num_int = book.num;
    NSNumber *num_n = [[NSNumber alloc] initWithInt:num_int];
    NSString *num_text = [num_n stringValue];
    cell.label3.text = num_text;

    return cell;
}
输入cell.label3.text的任何内容时,numTextField.text输出“0”。
我想将num_text存储到数据库中作为INTEGER,因为num将被添加并被一个按钮减去。

我对如何修复它的想法? 提前谢谢。

2 个答案:

答案 0 :(得分:0)

试试这个

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        Book* book = [self bookAtIndexPath:indexPath];
        cell.label1.text = book.title;
        cell.label2.text = book.time;

        int num_int = book.num;
        NSNumber *num_n = [[NSNumber alloc] initWithInt:num_int];
        NSString *num_text = [NSString stringWithFormate:@"%@",num_n]
        cell.label3.text = num_text;

    return cell;
}

答案 1 :(得分:0)

[NSString stringWithFormat:@"%d", count];