[Beauty pictures] iOS development technology sharing (1)-Ios local data storage

Source: Internet
Author: User

Preface:

I was an Asp.net programmer and later joined the iOS game development team. It has been more than a year now. In the past year, I went to bed every day until 2 or three o'clock, just to learn more. During this time, I learned everything, from C # To objective-C, to C ++, and gradually understood that programming really doesn't matter the language, as long as I am familiar with one language and want to get started with another language, it is really a very simple task. It takes half a month for you to get started with your work. (Of course, you can get started. It takes some time to study your skills ). What I want to say is that as long as you like it, programmers are not really a very hard job. On the contrary, I feel happy. Come on, programmers and friends!

After more than a month of work, I finally finished the [beauty pictures]. Next I will write some technical sharing articles, including the server and client, share the core code of this project. Please forgive me for saying something wrong and help me correct it. Thank you.

First, paste the project so that you can understand what this app is doing. This app has adapted to screens 5inch and 0inch. If it is represented in pixels, it is applicable to 320*480, 640*960, and 640*1136. It is posted on iPhone 5.

 

 

Beauty Appreciation, no yellow content, please feel free to download.

Here is: http://itunes.apple.com/cn/app/id590438908

I would like to invite you to join us and give us a high praise. Thank you very much.

 

IOS local data storage:

There are several common methods for iOS local data storage, such as plist, XML, nsuserdefaults, and keychain. However, each has its own characteristics, next I will briefly introduce nsuserdefaults and keychain, and give a demo to help beginners get started quickly.

 

1. nsuserdefaults

Generally, because the data stored by nsuserdefaults is not secure enough, you can modify the data according to your own needs. Therefore, nsuserdefaults is generally only used to store app setting data, this is like a cookie in the Web, which can also store data, but is not secure enough.

Code on

Setting. h:

1 # import <Foundation/Foundation. h> 2 3 typedef Enum {4 st_music = 100, 5 st_volume, 6 st_push, 7 st_num 8} settingtype; // enumeration of various settings 9 10 @ interface setting: nsobject11 // read getter12 + (bool) getisenablebytype :( settingtype) type; 13 // set setter14 + (void) setisenable :( bool) isenable bytype :( settingtype) type; 15 // clear data 16 + (void) resetdata; 17 18 @ end

Setting. Mm

1 # import "setting. H "2 3 # define key_setting @" beautypics _ "4 5 @ Implementation setting 6 7 + (void) resetdata 8 {9 for (settingtype = st_music; Type <st_num; type ++) {10 [setting setisenable: True bytype: type]; // default value: true11} 12} 13 14 + (bool) getisenablebytype :( settingtype) type15 {16 nsstring * Key = [key_setting stringbyappendingformat: @ "% d", type]; 17 ID isenable = [[nsuserdefaults standar Duserdefaults] objectforkey: Key]; 18 if (isenable = nil) {19 [[nsuserdefaults standarduserdefaults] setobject: [nsnumber numberwithbool: True] forkey: Key]; 20 [[nsuserdefaults standarduserdefaults] synchronize]; 21 return true; 22} 23 return [isenable boolvalue]; 24} 25 26 + (void) setisenable :( bool) isenable bytype :( settingtype) type27 {28 nsstring * Key = [key_setting stringbyappendingformat: @ "% d", typ E]; 29 30 if ([setting getisenablebytype: type]! = Isenable) {31 [[nsuserdefaults standarduserdefaults] setobject: [nsnumber numberwithbool: isenable] forkey: Key]; 32 [[nsuserdefaults standarduserdefaults] synchronize]; 33} 34} 35 @ end

The above code is clear at a glance. You must use [nsuserdefaults standarduserdefaults] synchronize] to synchronize the data after setting the data. Otherwise, the data will not be saved.

 

2. keychain

Since nsuserdefaults is not secure enough, are there some safe local data storage methods? The answer is yes, of course. This is the keychain, which can only be accessed by the app itself, other apps cannot be accessed (of course, you only need to set it now. However, to use this form: app1 agrees to app2 access, app2 can access the keychain stored in app1 ). There are a lot of articles about keychain. I will not repeat its principles. Here I will cite its usage. The storage method of keychain is also a dictionary, that is, nsmutabledictionary. The code below is as follows:

(1)Save data.Data can be nsarray, nsset, or nsdictionary. Generally, these three data structures are sufficient. The service is the key to store.

 

+ (void)saveData:(NSString *)service data:(id)data{    //Get search dictionary    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];    //Delete old item before add new item    SecItemDelete((CFDictionaryRef)keychainQuery);    //Add new object to search dictionary(Attention:the data format)    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];    //Add item to keychain with the search dictionary    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);}

 

(2)Read data. You can directly read the stored data by saving the data as the key.

+ (id)loadData:(NSString *)service{    id ret = nil;    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];    //Configure the search setting    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];    CFDataRef keyData = NULL;    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {        @try {            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)keyData];        } @catch (NSException *e) {            NSLog(@"Unarchive of %@ failed: %@", service, e);        } @finally {        }    }    if (keyData)        CFRelease(keyData);    return ret;}+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service{    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:                                  (id)kSecClassGenericPassword,(id)kSecClass,                                  service, (id)kSecAttrService,                                  service, (id)kSecAttrAccount,                                  (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,                                  nil];    return dict;}

  

(2)Demo. You can use keychain to read and store data. Next, let's take a short demo.

For example, if I want to store nsdictionary, the user name is "Atay", and the password is "123456", then:

1 nsdictionary * dict = [nsdictionary dictionary: @ "atai", @ "key_username", @ "123456", @ "key_pwd", nil]; 2 [keychain savedata: key_user_data_all data: dict];

Here, key_user_data_all is the key of the stored data. You can use this key to read the saved dictionary.

When reading, it is as follows:

1 NSDictionary * loadDict = [Keychain loadData: KEY_USER_DATA_ALL];

In this way, we can read the stored dictionary dict, And the things to do next will certainly become as desired.

Here is: http://itunes.apple.com/cn/app/id590438908

QR code download:

 

Not complete... The next article will introduce the use of the open-source class library asihttprequest and sdwebimage.

 

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.