IOS data storage methods and ios Data Storage Methods

Source: Internet
Author: User

IOS data storage methods and ios Data Storage Methods

IOS data storage is an important knowledge point for iOS application development:

There are many introductions on this aspect, but there is no comprehensive introduction to the usage of code layers. This article focuses on children's shoes that are a little familiar With iOS, and requires a certain understanding of the principles of CoreData. Currently, the following storage methods are available:

UT code to ensure correct use. Read the following:

#import <XCTest/XCTest.h>#import <sqlite3.h>#import "CoreDataHelper.h"@interface StudyUITests : XCTestCase@end@implementation StudyUITests- (void)setUp{    [super setUp];}- (void)tearDown{    [super tearDown];}-(void)testCoreData{    CoreDataHelper *coreHelper = [[CoreDataHelper alloc] init];    [coreHelper coreDataTest];}-(void)testSqlite3{    sqlite3 *db;        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];    NSString *databasePath = [documentPath stringByAppendingPathComponent:@"test.sqlite"];        NSLog(@"db path: %@",databasePath);            if(sqlite3_open([databasePath UTF8String], &db) != SQLITE_OK){        sqlite3_close(db);        NSLog(@"open sqlite fail!");        NSAssert(FALSE, @"create sqlite error");    }        NSString *sqlCreateTable = @"CREATE TABLE IF NOT EXISTS ptable (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, address TEXT)";    char *error;    if(sqlite3_exec(db, [sqlCreateTable UTF8String], NULL, NULL, &error) != SQLITE_OK){        sqlite3_close(db);        NSLog(@"can not create table.");        NSAssert(FALSE, @"create table error");    }        NSString *deleteAllSql = @"delete from ptable";    if(sqlite3_exec(db, [deleteAllSql UTF8String], NULL, NULL, &error) != SQLITE_OK){        sqlite3_close(db);        NSLog(@"delete values from table");        NSAssert(FALSE, @"delete values from table");    }        NSString *sql1 = [NSString stringWithFormat:                      @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",                      @"ptable", @"name", @"age", @"address", @"first name", @"23", @"pukou"];        NSString *sql2 = [NSString stringWithFormat:                      @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",                      @"ptable", @"name", @"age", @"address",@"second name", @"20", @"qixia"];        if(sqlite3_exec(db, [sql1 UTF8String], NULL, NULL, &error) != SQLITE_OK){        sqlite3_close(db);        NSLog(@"can not insert sql1");        NSAssert(FALSE, @"create insert db (sql1) error");    }        if(sqlite3_exec(db, [sql2 UTF8String], NULL, NULL, &error) != SQLITE_OK){        sqlite3_close(db);        NSLog(@"can not insert sql2");        NSAssert(FALSE, @"create insert db (sql2) error");    }            //Read data and check result.        NSString *query = @"select * from ptable";        sqlite3_stmt *statement;            if(sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, nil) == SQLITE_OK){        //start to traverse data                int size = 0;        while (sqlite3_step(statement) == SQLITE_ROW) {            size++;            char *name = (char*)sqlite3_column_text(statement, 1);            int age= (int)sqlite3_column_int(statement, 2);            char *address = (char*)sqlite3_column_text(statement, 3);                        NSString *nameStr = [[NSString alloc] initWithUTF8String:name];            NSString *addressStr = [[NSString alloc] initWithUTF8String:address];            NSLog(@"name: %@  age: %d address: %@",nameStr,age,addressStr);        }        NSAssert(size == 2, @"size should 2");    }else{        NSAssert(FALSE, @"query db error");    }    sqlite3_close(db);}-(void)testWriteToFile{    NSString *st1 = @"first";    NSString *st2 = @"second";        NSArray *array = [NSArray arrayWithObjects:st1,st2, nil];    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    NSAssert(path != nil, @"path is nil");    NSString *filename = [path stringByAppendingPathComponent:@"test.data"];    NSAssert([array writeToFile:filename atomically:YES],@"write successfully");        NSMutableArray *savearray = [NSMutableArray arrayWithContentsOfFile:filename];            NSAssert([[savearray objectAtIndex:0] isEqualToString:st1], @"not equal to str1");    NSAssert([[savearray objectAtIndex:1] isEqualToString:st2], @"not equal to str2");    }-(void)testUserDefault{    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    NSString *name = @"test";    [defaults setObject:name forKey:@"name"];        UIImage *image = [UIImage imageNamed:@"photo"];        NSData *imageData = UIImagePNGRepresentation(image);    [defaults setObject:imageData forKey:@"image"];        //now read from data            NSString *name1=  [defaults objectForKey:@"name"];    NSData *imageData1 = [defaults objectForKey:@"image"];        NSAssert([name1 isEqualToString:name], @"name1 is equal to test");    NSAssert([imageData1 isEqualToData:imageData], @"image data is not equal");    }-(void)testKeyedArchiver{    NSString *save1 =@"test1";    NSString *save2 =@"test2";            NSArray *array = [NSArray arrayWithObjects:save1, save2, nil];    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];            NSString *filename = [path stringByAppendingPathComponent:@"savedatatest"];    NSLog(@"filename : %@",filename);        //save data    NSAssert([NSKeyedArchiver archiveRootObject:array toFile:filename],@"archive successfully.");        array = [NSKeyedUnarchiver unarchiveObjectWithFile:filename];        save1 = [array objectAtIndex:0];        NSAssert([save1 isEqualToString:@"test1"], @"save1 must equals to test1");        save2 = [array objectAtIndex:1];    NSAssert([save2 isEqualToString:@"test2"], @"save1 must equals to test2");   }@end


The use of CoreData is a little complicated, so it is put into the Helper class separately. Entity model contains three attributes: name, age, and address. You can create a test project and generate an Entity object.
#import "CoreDataHelper.h"#import <CoreData/CoreData.h>#import "Entity.h"@interface CoreDataHelper()@property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;@property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;-(NSPersistentStoreCoordinator *)persistentStoreCoordinator;-(NSManagedObjectContext *)managedObjectContext;-(NSManagedObjectModel *)managedObjectModel;@end@implementation CoreDataHelper-(void)coreDataTest{    NSError *error = nil;    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:self.managedObjectContext];    NSFetchRequest *request = [[NSFetchRequest alloc] init];    [request setEntity:entityDescription];        NSArray *oldResult = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];    for (Entity *bb in oldResult) {        [self.managedObjectContext deleteObject:bb];    }    NSAssert([self.managedObjectContext save:&error], @"deleting.....");            /******insert *****/    Entity *entity = [[Entity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];        entity.name = @"test";    entity.age = [NSNumber numberWithInt:20];    entity.address = @"beijing";    [self.managedObjectContext insertObject:entity];    NSAssert([self.managedObjectContext save:&error], @"inserting.....");            /*****query *****/    NSSortDescriptor *sortDescription = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO];    NSArray *sortDescriptions = [[NSArray alloc] initWithObjects:sortDescription, nil];    [request setSortDescriptors:sortDescriptions];        NSMutableArray *array = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];        for (Entity *bb in array) {        NSLog(@"name: %@ age:%@ address:%@",bb.name,bb.age,bb.address);    }    NSAssert([array count] == 1, @"count size is equal to 1");            /***** update and check****/    NSArray *updateResult = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];    Entity *first = [updateResult objectAtIndex:0];    first.name = @"one";    NSAssert([self.managedObjectContext save:&error], @"updating.....");            updateResult = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];    first = [updateResult objectAtIndex:0];    NSAssert([first.name isEqualToString:@"one"], @"need to equeal one");        /**** insert and check ****/    entity = [[Entity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];        entity.name = @"test2";    entity.age = [NSNumber numberWithInt:23];    entity.address = @"nanjing";    [self.managedObjectContext insertObject:entity];    NSAssert([self.managedObjectContext save:&error], @"inserting.....");    array = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];    for (Entity *bb in array) {        NSLog(@"name: %@ age:%@ address:%@",bb.name,bb.age,bb.address);    }    NSAssert([array count] == 2, @"now size is equal to 2");        }-(NSPersistentStoreCoordinator *)persistentStoreCoordinator{    if(_persistentStoreCoordinator)        return _persistentStoreCoordinator;            NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];        NSURL *storeURL = [NSURL fileURLWithPath:[documentPath stringByAppendingPathComponent:@"person.sqlite"]];        NSError *error = nil;        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];            if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]){        NSLog(@"persistent error : %@",[error userInfo]);    }    return _persistentStoreCoordinator;}-(NSManagedObjectContext *)managedObjectContext{    if(_managedObjectContext)        return _managedObjectContext;        NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];        if(coordinator){        _managedObjectContext = [[NSManagedObjectContext alloc] init];        [_managedObjectContext setPersistentStoreCoordinator:coordinator];    }    return  _managedObjectContext;}-(NSManagedObjectModel *)managedObjectModel{    if(_managedObjectModel)        return _managedObjectModel;        NSURL *modeUrl = [[NSBundle mainBundle] URLForResource:@"Entity" withExtension:@"momd"];    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modeUrl];    return  _managedObjectModel;}@end




How to implement data storage in IOS development

Select an appropriate data storage method based on the specific business scenario. [*] (1) Default user settings-in this case, user intervention is usually not required, such as game clearance information, Video playback records, or when the App exits, you want to recover to exit. [*] (5) remote database-generally, the App calls the remote RESTFulWCF service and transmits JSON or XML data to the remote Web service, the logic for reading and writing databases is fully implemented on the Web server.

Several simple methods for transferring data between mobile phones and computers

Files, photos, documents, music, e-books, videos, and other digital data are usually stored on mobile phones, tablets, PCs, and other devices. Do you know how to quickly and conveniently send files from Android smartphones to iPad? How Can I copy and paste a long article stored in my laptop on my iphone? The following describes several convenient methods for transferring files and data between computers and mobile phones through Web terminals and smart phone apps. All users who use desktop applications are familiar with this method of transferring files through Email. The file is from a device and then downloaded to another device. You can also transmit data through Dropbox, Google Drive, SkyDrive, and other cloud data storage services. You can even use Web applications without using software to transmit data between different devices. If you use "ge. tt", you can upload data in a browser and then download the data from another device in a browser. In addition, "JustBeamIt" does not have to worry about the server sending data directly when you want to read data, and there is no file size limit. When Google Keep is used to send notepad content, Google Keep is the most convenient. Record, copy, and paste on Google Keep directly, and you can view it on other devices immediately. This is a service used on the Web side, but it can also be used as an Android Application. I sent a long password entered through the address bar and mobile phone from my computer to my mobile phone. There are several other applications that can send links and notebooks, such as "Hopper" and "MoPad. If the Android system is used, AirDroid will be used by Android users. It is estimated that only "AirDroid" is enough to send and receive files on mobile phones. After starting AirDroid, you can upload or download files and folders in the Android system to your computer through a browser. However, mobile phones and computers must use the same Wi-Fi network at the same time. "Super Beam" can also be used for data transmission between two Android devices ". After selecting several files from the file management application, select SuperBeam In the Android sharing menu to generate the corresponding QR code. The other device runs SuperBeam and reads the sender's QR code to automatically transfer the file. If two Android devices do not have the same wi-fi connection, use Wi-Fi Direct to send files. For Mac systems, you can use Droid NAS and Documents apps. If you use Mac, what will happen if you download "Droid NAS? Find your Android phone or tablet in the Finder and use Wi-Fi to transfer files easily. For Apple, unlike Android, there is no iOS-specific file system except for the media library. It is better to use the Documents app to transfer Documents, photos, and other files from your computer to your iPad and iPhone through Wi-Fi. Through this APP, files can be uploaded from the computer to the network driver and then to the iOS device. Is it better to use Bump or Hoccer for transmission between Android and iOS? Files cannot be transmitted through Bluetooth in iOS. When photos and videos are removed from iPhone and iPad albums, is it easier to use Dropbox? For a single file, ge. tt and DropCanvas.com are also applicable. We recommend that you use mobile apps such as "Bump" and "Hoccer" when transferring files between Android and iOS, or between your computer and mobile phone. When using Bump, select the file on the mobile phone and press the null delimiter on the mobile phone. Then, the file is immediately displayed in the browser of the computer. Hoccer uses two mobile phones to move photos from one device to another. The first time I used this application, I was taken aback.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.