iOS开发之Realm数据库第一篇

来源:互联网 发布:java files运用失败 编辑:程序博客网 时间:2024/05/17 21:49

简介:主要讲解Realm数据库的安装,Realm数据库的基本操作,并且通过一些实例来完成数据的增删改查,以及数据库的基本配置。让你从开始接触到上手使用,只需短短几分钟。

Realm的特性
移动设备支持:realm是第一个针对手机平板和可穿戴设备设计的数据库,基本全平台支持。
简单:Realm的安装和接入简单,不同于core Data,不需要开发者配置模型层结构,从开始接触到上手使用,只要短短几分钟时间。
现代:关系型数据库,支持泛型
快速:官方称比SQLite的常规操作更快速

Cocoapods引入Realm

Podfile文件

platform :ios, "8.0"source 'https://github.com/CocoaPods/Specs.git'use_frameworks!target :'Realm数据库' do pod 'Realm'end

注:如何安装使用CocoaPods,请参考另一篇文章:
http://blog.csdn.net/wtdask/article/details/74645581

.h文件

#import "ViewController.h"@import Realm;@interface ViewController ()@end//创建Dog模型@interface Dog : RLMObject@property NSString * name;@property NSInteger age;@end//创建主人模型RLM_ARRAY_TYPE(Dog);@interface Person : RLMObject@property NSString * name;@property RLMArray<Dog*><Dog> * dogs;@end@implementation Dog@end@implementation Person@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    //创建一个数据库,记录狗狗的名字和年龄    Dog * dog =[[Dog alloc] init];    dog.name = @"perter";    dog.age = 1;    //添加一个主人的记录    Person * owner =[[Person alloc] init];    owner.name = @"Mike";    [owner.dogs addObject:dog];    NSLog(@"%@",owner);    //查询年龄小于2岁的狗狗    RLMResults * result =[Dog objectsWhere:@"age < 2"];    NSLog(@"%@",result);    //添加狗狗狗    RLMRealm * r = [RLMRealm defaultRealm];    //使用block方式或者使用下面的方式    [r transactionWithBlock:^{        [r addObject:dog];    }];    NSLog(@"%@",result);//    [r beginWriteTransaction];//    在中间写数据库的操作//    [r commitWriteTransaction];    //线程操作    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//        RLMRealm * r =[RLMRealm defaultRealm];//        //        [r beginWriteTransaction];//        [r commitWriteTransaction];    });}
原创粉丝点击