iphone 跳转之间数据传值

我们经常会用的view之间跳转的时候进行传值的操作。。。

利用AppDelegate进行传值:

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
    NSString *name; //我们将内容保存在这里。。。
}

 接着

AppDelegate.m

@synthesize name;
 

下面是viewcontroller之间的值传递。。。

存值:

 //将值放到AppDelegate中
 AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    appDelegate.name = @"http://751401909.iteye.com";

 取值:

//用到的地方取出来
 AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSLog(@"name:%@",appDelegate.name);

 这是一种方法。。。当然也有其他方法。。

使用NSUserDefaults:

如果仅是传值,有点大材小用了。。。他可以传递对象数据。。

得到NSUserDefaults:

//得到对象
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults] ;
 

存储:

//setObject 是存储的内容  forKey 是标记  取得时候用
[userDefaults setObject:[text1 text] forKey:k1] ;

 取值:

//根据key找到存储的数据 跟android的sharedpreferences类似
text1.text = [userDefaults objectForKey:k1] ;

 也比较简单。。。

数据库传递:

这里涉及数据库的操作。。需要libsqlite3.0.dylib 并包含sqlite3.h。。。

为了方便;

#define DATABASE_NAME @"test.wp" //数据库名字

#define TABLE_NAME @"table_tf" //表名

#define ROW_NUMBER @"content"  //字段

#define ROW_TIME @"time"  //字段
 

主要代码片段:

创建数据库和表:

@property sqlite3 *database ;

@property NSString *dbPath ;
.....
.....
-(void) initDataBase{

    //找到应用程序的路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;
    
    NSString *documentPath = [paths objectAtIndex:0] ;
    
    
    dbPath = [documentPath stringByAppendingPathComponent:DATABASE_NAME] ;
    
    
    
    int result = sqlite3_open([dbPath UTF8String], &database) ;
    
    if(result == SQLITE_OK){
        
        NSString *sqlCreateTable = [[NSString alloc] initWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (%@ TEXT ,%@ TEXT)",TABLE_NAME,ROW_NUMBER,ROW_TIME];
        
        
        [self sqlExc:sqlCreateTable] ;
        
        NSLog(@"数据库创建成功") ;
    }
    
    sqlite3_close(database) ;

}

 保存数据:

sqlite3_open([dbPath UTF8String], &database) ; //打开数据库
    //清空一下表  可以不写
NSString *str = [[NSString alloc] initWithFormat:@"DELETE FROM %@",TABLE_NAME] ;
    
[self sqlExc:str];  //自己定义的方法。。 下面有
.....
.....
NSString *sql = [[NSString alloc] initWithFormat:@"INSERT INTO %@ (%@,%@) VALUES('%@','%@')",TABLE_NAME,ROW_NUMBER,ROW_TIME,tempStr,time] ;

[self sqlExc:sql] ;  //插入数据

sqlite3_close(database) ; //关闭数据库



-(void)sqlExc:(NSString *)sql{

    char *err;
    
    int result = sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) ;
    
    if (result != SQLITE_OK) {
        NSLog(@"数据库操作数据失败!   errCode:%d msg:%s",result,err);
    }

}
 

也是刚开始学习 ,,,不知道还有没有其他的好的方法。。。  如果有好的方法,,务必留言哦  共同学习。。。

贴一详细使用方法。。。GO

猜你喜欢

转载自751401909.iteye.com/blog/1751520