本篇主要是總結:1.自己在過去一年以來的學習經驗以及不足;
2.接下來應該怎么去學習,學習那些方面
所取得的成績
1.基本屬性的運用。
strong,weak,copy,assign,nonatomic,atomic,copy
等屬性修飾的作用有了一個比較明確用法。一般默認的是strong
,也就是強引用,而為了避免循環引用時,用weak
,修飾string
時,用copy
,以得到新的內存分配,而不只是原來的引用。所有的屬性,都盡可能使用nonatomic,以提高效率,除非真的有必要考慮線程安全。有關copy,retain,assign
,retain是指針拷貝,copy是內容拷貝,使用assign
: 對基礎數據類型 (NSInteger)和C數據類型(int, float, double, char
,等)。在拷貝之前,都會釋放舊的對象。,可以參考OC中assign、copy 、retain等關鍵字的含義.
2.OC中頁面的傳值
OC中傳值我現在熟悉的有1.屬性傳值;2.代理傳值 3.通知傳值 4.block傳值 5.全局變量 可以參考這篇淺談iOS常用的幾種傳值方式
3.數據的存儲方式 轉自:iOS 數據存儲的常用方式
1.xml屬性列表(plist)歸檔
只能存儲基本數據類型(NSString、NSDictionary、NSArray、NSData、NSNumber
)
NSString *docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];
// 拼接要保存的地方的路徑
NSString *filePath = [docPathstringByAppendingPathComponent:@"str.plist"];
// 1、寫入數據
[array writeToFile:filePath atomically:YES];
// 2、 讀取數據
NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
2.偏好設置
UserDefaults設置數據時,不是立即寫入,而是根據時間戳定時地把緩存中的數據寫入本地磁盤。所以調用了set方法之后數據有可能還沒有寫入磁盤應用程序就終止了。出現以上問題,可以通過調用synchornize方法強制寫入
用法:
NSUserDefaults *UserDefaults = [NSUserDefaultsstandardUserDefaults];
// 1、寫入
[UserDefaults setBool:NO forKey:@"isLogined"];
// 強制寫入
[defaults synchornize];
// 2、讀取
BOOL isVisble = [UserDefaults boolForKey:@"isLogined"];
其實,它存儲的就是一個字典
3.歸檔與反歸檔
基本使用:需要歸檔的模型類必須要遵守NSCoding
協議,然后模型實現類中必須實現兩個方法
:1>encodeWithCoder ->歸檔
;2> initWithCoder: - > 解檔
使用注意
如果父類也遵守了NSCoding協議,請注意:
應該在encodeWithCoder:方法中加上一句
[super encodeWithCode:encode]; // 確保繼承的實例變量也能被編碼,即也能被歸檔
應該在initWithCoder:方法中加上一句
self = [super initWithCoder:decoder]; // 確保繼承的實例變量也能被解碼,即也能被恢復
示例
// 1. 自定義模型類Person
// 1.1 Person.h文件
#import <Foundation/Foundation.h>
// 只要一個自定義對象想要歸檔,必須要遵守NSCoding協議,并且要實現協議的方法
@interface Person : NSObject<NSCoding>
@property (nonatomic, assign) int age;
@property (nonatomic, strong) NSString *name;
@end
// 1.2 .m實現文件
#import "Person.h"
#define KName @"name"
#define KAge @"age"
@implementation Person
// 什么時候調用:當一個對象要歸檔的時候就會調用這個方法歸檔
// 作用:告訴蘋果當前對象中哪些屬性需要歸檔
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:KName];
[aCoder encodeInt:_age forKey:KAge];
}
// 什么時候調用:當一個對象要解檔的時候就會調用這個方法解檔
// 作用:告訴蘋果當前對象中哪些屬性需要解檔
// initWithCoder什么時候調用:只要解析一個文件的時候就會調用
- (id)initWithCoder:(NSCoder *)aDecoder
{
#warning [super initWithCoder]
if (self = [super init]) {
// 解檔
// 注意一定要記得給成員屬性賦值
_name = [aDecoder decodeObjectForKey:KName];
_age = [aDecoder decodeIntForKey:KAge];
}
return self;
}
@end
// 2. 實例 -》基本使用:取 / 存 數據
// 歸檔
[NSKeyedArchiver archiveRootObject: self.persons toFile:KFilePath];// 將self.persons模型對象數組
// 解檔
_persons = [NSKeyedUnarchiver unarchiveObjectWithFile:KFilePath];