iOS 轻量数据存储

在北京实习的几个月里,第一次接触OC。之前有接触iOS,但码代码不是很多,也只是学校的一个小项目,当时还是swift1.0版本。

这次总结的是iOS的轻量级数据存储,如果说你要给你的app存储一些账号密码,一些设置的开关(true false)之类的很小的数据,以供下次读取,建议使用NSUserDefaults类。

先来看一下苹果的官方解释:
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a user’s preferences. For example, you can allow users to determine what units of measurement your application displays or how often documents are automatically saved. Applications record such preferences by assigning values to a set of parameters in a user’s defaults database. The parameters are referred to as defaults since they’re commonly used to determine an application’s default state at startup or the way it acts by default.

At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user’s defaults database.

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.

简单来说,OC提供这个类让你的app可以以直接赋值的方式将数据存储到用户的默认数据库里。下次要用到你存储的数据时,直接使用NSUserDefaults对象去读就行了。Synchronize这个方法是把缓存和数据库进行同步。NSUserDefaults 能存的数据类型有:floats, doubles, integers, Booleans, and URLs等。记得NSUserDefaults是一个单例,是线程安全的,在整个程序中只有一个实例对象。

一. 缓存普通数据

1. 存储:

 

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

[userDefaults setBool: NO forKey:IMAGES_DISPLAY_KEY];

[userDefaults setFloat: myFlout forKey:MY_FLOAT];

[userDefaults setObject:listData forKey:BANNER_IMAGE];

 

记得再赋值后调用synchronize方法,不然数据不会同步到数据库里。

 

[userDefaults synchronize];

 

存储方法除了这三种还有:setInteger:forKey、setDouble:forKey、setURL:forKey 。大家选择相应的方法使用。

2.读取:

 

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

_imageDisplayOrNotSwitch.on = [_userDefaults boolForKey:IMAGES_DISPLAY_KEY];

_myFlout = [_userDefaults floatForKey:MY_FLOAT];

NSData* listData = [[NSUserDefaults standardUserDefaults] objectForKey:BANNER_IMAGE];

 

这样就方便地完成读取了。值得一提的是 IMAGES_DISPLAY_KEY,MY_FLOAT,BANNER_IMAGE这三个key我都存在了另一个文件里,LocalDataKey.h。所以记得import LocalDataKey.h。

LocalDataKey.h 里是这样的

 

#ifndef LocalDataKey_h

#define LocalDataKey_h

#define BANNER_IMAGE @”BannerImage”

#define IMAGES_DISPLAY_KEY @”ImageDisplayKey”

#define MY_FLOAT @”MyFloat”

 

如果有其他的想存储的数据,也可以将key存在这个里面,简单方便。值得注意的是要保证每个key的唯一性,不能有重复,不然会出现数据混淆或错误。

还有一点值得说明的是,NSUserDefaults存储的值是immutable的,是不可变的。比如你要存储一个NSMutableArray的array,你需要重新建立一个array:

 

NSArray * array = [NSArray arrayWithArray:mutableArray];

 

再将array使用 [user setObject:array forKey:@”blablabla”]; 存数据,别忘了使用synchronise方法同步到数据库。

二. 缓存自定义对象

实际上NSUserDefaults不支持存储自定义对象, 但支持存储NSData,举个我实习时的例子:

BBBanner.h

 

#import@interface BBBanner : NSObject

@property (retain,nonatomic) NSString *title;

@property (retain,nonatomic) NSString *href;

@property (retain,nonatomic) NSNumber *type;

@property (retain,nonatomic) NSString *src;

@end

 

很多人看到这里会想不到下一步会做什么,我们需要做的是将BBBanner这个类型变成NSData。这一步叫归档。首先在.h 文件中申明 NSCoding 协议,再 在 .m 中实现 encodeWithCoder 方法和initWithCoder 方法。实现如下:

BBBanner.m:

 

#import “BBBanner.h”

#define kType @”BannerTypeKey”

#define kSrc @”BannerSrcKey”

#define kTitle @”BannerTitleKey”

#define kHref @”BannerHrefKey”

@implementation BBBanner

– (void)encodeWithCoder:(NSCoder *)aCoder

{

[aCoder encodeObject:_type forKey:kType];

[aCoder encodeObject:_src forKey:kSrc];

[aCoder encodeObject:_title forKey:kTitle];

[aCoder encodeObject:_href forKey:kHref];

}

– (id) initWithCoder:(NSCoder *)aDecoder

{

self = [[BBBanner alloc] init];

self.type = [aDecoder decodeObjectForKey:kType];

self.href = [aDecoder decodeObjectForKey:kHref];

self.title = [aDecoder decodeObjectForKey:kTitle];

self.src = [aDecoder decodeObjectForKey:kSrc];

return self;

}

@end

 

这样就将BBBanner这个类型转换成NSData了。

接下来我们实现存储:

 

BBBanner* banner = [[BBBanner alloc] init];

banner.title = @”hi title”;

banner.href = @”hi href”;

banner.type = 1;

banner.src = @”www.google.com”;

//使用archivedDataWithRootObject转换类型

NSData *bannerData = [NSKeyedArchiver archivedDataWithRootObject: banner];

[bannerDataArray addObject:bannerData];

[_userDefaults setObject:bannerData forKey:BANNER_DATA];

[_userDefaults synchronize];

 

这样就成功的把banner的类型存进NSUserDefaults啦。同样也可以转换一个里面全是banner类型的NSMutableArray。比如:

 

NSArray* bannerModels = [BBBanner mj_objectArrayWithKeyValuesArray: dic]; //dic是从网络上请求过来的NSDictionary,mj_objectArrayWithKeyValuesArray是一个引用的库里的方法,可以将一个array里的object类型通过dic转换成BBBanner或者是任意一个你自己创建的类型,像上面一样记得归档。

NSData *listData = [NSKeyedArchiver archivedDataWithRootObject: bannerModels];

 
实现读取:
NSData* bannerData = [[NSUserDefaults standardUserDefaults] objectForKey:BANNER_DATA];

//使用unarchiveObjectWithData将数据类型转换回去
BBBanner* banner = [NSKeyedUnarchiver unarchiveObjectWithData:bannerData];

过些时间我会考虑加上存储整个包含自定义类型的数组的实现方法,其实大同小异。

三. 有些人会问 存储的数据到底去哪里了?

这个我也是上网搜了其他的文章才大概有点了解。

它存储在应用程序内置的一个plist文件里,这个可以根据路径看到。详见 http://blog.csdn.net/enuola/article/details/7959767
四.其他的有可能用到的方法

containsObject方法。贴上一段小代码:
if([_userDefaults.dictionaryRepresentation.allKeys containsObject:PUSH_NOTIFICATION_KEY])

{

_pushNotifSwitch.on = [_userDefaults boolForKey:PUSH_NOTIFICATION_KEY];

}

else

{

_pushNotifSwitch.on = YES;

}

这个方法是查找是否有无你需要的key,如果没有,你就有可能读取到NULL,然后导致程序crash之类的。还是挺值得注意的一个方法。

大概要说的就这么多。

Wednesday writing week10

In preparation for the final reflection paper, start by thinking back on your work this quarter. What was most challenging? What did you enjoy? What did you learn about writing from trying to work with real communities/organizations?

 

The most challenging thing me is to understand our audiences and find out what they need and also incorporate those things into our writing. We did researches and surveys to find data and try to support our arguments. I think that is the most challenging part in the writing. What I enjoyed very much is the process we create our own solutions on advertisement of GHI, we discussed several methods and finally I think we made a good job.

Working with real communities is really a great experience, I think focusing on audience is an important aspect. I also learnt how work in a group. I learnt how to combine our research into our paper and express our ideas creatively and also, targeted on our audiences.

WED WRITING WEEK 8

Based on your work and on the peer review, reflect on your sample documents. What do you think is especially effective, successful, and compelling about your draft? What do you think may be awkward, confusing, boring or otherwise ‘not working’ about your draft.

For the email, we provide a limited colour combination but it clearly shows the key point of GHI. The more effective part is that we have the great pictures with the concise words to better represent the services from GHI.

The awkward part might be that when we put the aetna logo with GHI logo together, it seems somewhat weird because one is rectangle while another is purely squared, so we should build a better arrangement and layout. Secondly, in the services part, the words and pictures  are too close to each other and seems a little crowded.

For the insurance card, the successful part would be that we provide both clear and simple information of user info as well as the services provided by GHI, we design it with a table and make it easy for audiences to acquire the important informations.

Yet, the layout of insurance card can be improved, we can get more space on the edge of the back of the card and change the font a little bit to fit the new layout.

Wed Writing Week 7

Explain the key information design strategies that you learned in the texbook and how you plan to apply these designing your 2 example documents in a usable and accessible way?

  1. grouping content rhetorically
  2. organizing content visually(can enhance contrast or key points)
  3. signaling structural relationships

For insurance card, we need to provide the information as concise as possible—-we don’t want to put too much unnecessary things in a small space to mess it up. For example, put ID, name, services, prices, contact number and some other important info on the obvious place, use different colours and fonts to highlight those staff. The font size should be appropriate,  we should make it easy for audiences to read. For different group of information, we can use space to separate them and divide them into different clusters. We should also consider the integral beauty, like margin, spaces between different parts, symmetry should be considered carefully.

For the email, we can provide much more information than the insurance card does. First we can make a more attractive form with some certain colours in background. We will try to use different colour combinations and see which one is better for appealing audiences and build a relationship with them. Then we want to present our content in a clearer way. For the subpoints or coordinate explanations, we can use bulleted lists or tables to make our email easier to read. Intentional space will also be an important bridge to jump from one point to the other. Fonts and font size are also important parts, we should make it more efficient for readers to read and size should also be proper so that audiences can read easily, quickly and will not get tired of it.

Wednesday Writing Week6

  1. Define the genres that you will make for the final project.
  2. Locate 1 and share good examples of each genre. (I recommend that each group member find different good examples).
  3. Identify and explain several key writing or design choices that you think are effective. This means that you should both define a writing/design choice from your examples and explain why you think it is effective.

1. The genres that we will make for the final project is mail & Insurance card.

2. Good example for email:

Screen Shot 2016-05-03 at 11.13.18 PM

Good example for info card:

2013_Generic_NA_ID_Card_325x353

3.

For the email, the one above has several advantages: It has a coloured background, in the middle is a white paper with black words, this contrast emphasize the words part and let audiences focus on the content the email tries to convey; Secondly, it uses body font to underscore the key items, so viewers can get a better understanding on the content, like which one is more important, also the author uses the bullets to show different supporting ideas, making the emails clear and much more effective.

For the insurance card, it limits the choices of colour to make the card simple and easy to read; It takes use of several horizontal lines to separate different parts, we can see name and id are in the same part while the costs for each service are in right hand part, it becomes really convenient to read when we separate the contents wisely. Also, in the writing of the insurance card above, we can’t find any lengthy sentence inside, it keeps using the short term of words and makes the card cleaner, simpler and much more accessible than the other cards.

 

 

 

Wednesday Writing Week4

Reflect upon the contexts in which you write. What spaces/places are most/least productive for you? What genres do you write the most? How much time to you spend writing to communicate interpersonally; writing to aid your studying; or writing to compose polished documents for real audiences? What tools, strategies, or interfaces are important for your writing process?

About the contexts where I wrote, I would say website, blog, socialisation on internet, email that communicate with professors, cover letter, and assignments from the classes. The places that are quite and not crowded will make me productive, like the library on Sunday. My home is least productive for me. I write papers(like artistry paper) most. I spend one hour per day to communicate interpersonally; few hours a week to aid my studying; very few time to compose polished documents for real audiences, I rarely do that but I think it’s a really meaningful and interesting thing. Acquiring the informations and doing research, hearing advices from my friends and internet is really important for my writing process.

Wednesday Writing #3

1. Reflect: The reading for this week discussed rhetorical theories. What theories may inform the work you do with your group project? What theories or values may inform the technical communication of your community or organization? This is an intentionally open-ended question. You should spend some time reflecting on the reading and how this may inform your group project.

Hi, I am from group 4 and our group project is dealing with the problems from UCSB Student Health Centre. The health problem is always an important aspect of human’s life. The theories or the ideas like “who will go UCSB Student Health” or “who needs the Student Health service” and “how to help them get a more convenient services from Student Health centre” or “how to strengthen the importance of health for students”will direct me to the way about what work should I do in my project. We are considering making posters or doing articles on the websites to let students know how to help their own body. More importantly, the audiences might be a key part in this process and informs the technical communication of our community. Some students don’t always see the websites and cannot get access to the services from UCSB Student Health, so the email might be a efficient way of informing them. On the other hand, the doctors, or the Student Health Staffs might face the more difficult situations than students do, like writing the reports of appointments schedule problems when there are too many appointments aw well as writing the analysis of patients’ diseases and in fact they have more writing situations than students do. This inspires me to think the way to help them. Also, the theories like “does student know the benefits they have in Student Health Centre?” Most students have the health insurance and some of them can get the free services like regular dental cleanings and exams, which are really helpful but some of them does not even know. The relevant idea might be “Are the insurance necessary for students?”Those might be other directions of informing the work I do with group project.

2. Plan: You will need to find some research to inform your white paper. To prepare for this: 1) define the problem that you will research 2) find 1 or 2 credible resources that may help you understand the problem.

  1. Does everyone in universities does have a health insurance?
  2. source: http://scholars.unh.edu/cgi/viewcontent.cgi?article=1226&context=honors