data-persistence

Sandbox(沙盒机制)

iOS中得沙盒机制(sandbox)是一种安全体系,它规定了应用程序只能在为该应用程序创建的文件夹内读取文件,不可以访问其他地方的内容。所有的非代码文件都保存在这个地方,如图片,声音,属性列表和文本文件等。

  • 每个应用程序都在自己的沙盒内
  • 不能随意跨越自己的沙盒去访问别的应用程序的沙盒内容
  • 应用程序向外请求或接受数据都需要经过权限认证

    一个沙盒中包含四部分

    • .app文件,即可运行的应用文件;
    • Document,苹果建议将程序创建或程序浏览的文件数据保存在该目录下,iTunes备份和恢复时会包括该目录;
    • Library,存储程序的默认设置或其它状态信息;
    • Library/Caches,存放缓存文件,iTunes不会备份此目录,此目录下的文件不会在应用退出删除;
    • tmp,创建和存放临时文件的地方,iTu不会备份此目录。

代码获取沙盒路径的方法

  1. 获取根目录

    NSString *homePath = NSHomeDirectory();

  2. 获取Document目录
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];

  3. 获取Cache目录
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)[0];

  4. 获取Library目录
    NSString *libPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)[0];

  5. 获取tmp目录
    NSString *tmpPath = NSTemporaryDirectory();

iOS数据持久化技术

数据持久化既是,能将内存中的数据模型转换为存储模型,并能在将来需要时将存储模型还原为数据模型的一种机制。

说明 : 通俗的讲,也就是将数据保存在非易失性的设备中,并且能在需要时恢复。针对苹果设备来说,就是从闪存到内存的过程。

iOS开发中数据持久化的方法

  • Row File APIs(C语言的文件操作,iOS的NSFilemanager)
  • NSUserDefaults (默认保存文件在对应的程序包sandbox的目录下的library/Preferences)
  • Plist(属性列表)
  • NSCoding + Archiver&Unarchiver (对象归档)
  • SQLite (数据库)
  • FMDB (对SQLite的封装)

@property (nonatomic, strong) NSString *filePath;
@property (nonatomic, strong) UITextField *textField;

#define kFileName                 @”test.txt”


ROW APIs

C语言文件操作### ROW APIs

  1. 创建文件路径
1
2
3
4
5
6
//创建文件存放路径(一般需要保存的文件存放在sandbox的Document目录下)
- (void)setupPath
{
NSString *documentDirectory = NSSearchPathForDirectorieInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];
self.filePath = [documentDirectory stringByAppendingPathComponent:kFileName];
}
  1. 文件的写入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- (void)saveData
{
// oc文件路径转化为c
const char *filePath = [_filePath UTF8String];
// 打开文件
FILE *fp = fopen(filePath, "w+");
if (NULL == fp) {
perror("fopen");
return;
}
// 将_textFiled的内容写到文件
const char *content = [_textField.text UTF8String];
size_t size = fwrite(content, BUFSIZE, 1, fp);
fclose(fp);
if (size > 0) {
 NSLog(@"Saved data successfully");
}
}
  1. 文件的读取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
- (void)loadData
{
// 文件路径
const char *filePath = [_path UTF8String];
NSLog(@"%s", filePath);
// 打开文件
FILE *fp = fopen(filePath, "r");
if (fp == NULL) {
perror("fopen");
return;
}
//读取文件内容到内存
char buf[BUSIZ] = {0};
//获取文件大小
fseek(fp,SEEK_END);
long size = ftell(fp);
fread(fp,size,1,buf);
//赋值给_textField
NSString *str = [NSString stringWithUTFString:str];
if(str != NULL && ![str isEqualToString:@""]);{
_textField.text = str;
}
fclose(fp);
}

OC NSFileManager文件管理器操作

  1. 创建文件路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//创建文件存放路径(一般需要保存的文件存放在sandbox的Document目录下)
- (void)setupPath
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentDirectory = NSSearchPathForDirectorieInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];
//创建文件目录
NSString *test = [documentDirectory stringByAppendingPathComponent:@"test"];
[fileManager createDirectoryAtPath:test withIntermediateDirectories:YES attributes:nil error:nil];
self.filePath = [documentDirectory stringByAppendingPathComponent:kFileName];
NSString *content = nil;
if(![fileManager fileExistsAtPath:self.filePAth]){
[fileManager createFileAtPath:self.filePath contents:[content dataUsingEncoding:NSUTF*String] attributes:nil];
}
}
  1. 文件的写入
1
2
3
4
5
6
7
8
9
10
- (void)saveData
{
NSError *error;
[self.textField.text writeToFile:self.filePath atomically:YE];
if(error){
NSLog(@"Error : %@",error);
return;
}
NSLog(@"save data successfully");
}
  1. 文件的读取
1
2
3
4
5
6
7
8
9
10
11
- (void)loadData
{
NSError *error;
NSString *content = [[NSString alloc]initWithContentsOfFile:self.filePath encoding:NSUTF*String error:&error];
if(error){
NSLog(@"Error : %@",error);
return;
}
self.textField.text = content;
NSLog(@"load data successfully");
}

NSUserDefaults

>

  • 直接使用原始的文件操作API,不管是C语言的还是OC的都不太方便
  • Cocoa会为每个app自动创建一个数据库,用来存储App本身的偏好设置,如:开关
    值,音量值之类的少量信息

  • NSUserDefaults使用时用 [NSUserDefaults standardUserDefaults] 接口获取单例对象

  • NSUserDefaults本质上是以Key-Value形式存成plist文件,放在App的 Library/Preferences目录下
  • 这个文件是不安全的,所以千万不要用NSUserDefaults来存储密码之类的敏感信息,用户名和密码应该使用KeyChains来存储
  1. 文件的写入
1
2
3
4
5
6
7
8
9
10
11
12
- (void)saveData
{
NSUserDefaults *userDefaults = [NSUserDefaults
standardUserDefaults];
float progress = [self.progressTextField.text floatValue];
[userDefaults setFloat:progress forKey:@"progress"];
[userDefaults setObject:self.inputTextField.text
forKey:@"input"];
database
// keeps the in-memory cache in sync with a user’s defaults
[userDefaults synchronize];
 }
  1. 文件的读取
1
2
3
4
5
6
7
8
9
10
11
- (void)loadConfig
{
NSUserDefaults *userDefaults = [NSUserDefaults
standardUserDefaults];
self.toggle.on = [userDefaults boolForKey:@"toggle"];
self.progressView.progress = [userDefaults
floatForKey:@"progress"];
self.progressTextField.text = [NSString stringWithFormat:@"%.2f",
self.progressView.progress];
self.inputTextField.text = [userDefaults stringForKey:@"input"];
}
**说明:** *对NSUserDefaults单例对象的操作,实质上还是对PList文件 (Library/Preferences/<Application BundleIdentifier>.plist)的读写,只是Apple帮我们封装好了 读写方法。*

Plist

>

  • NSUserDefaults只能读写Library/Preferences/.plist这个 文件
  • PList文件是XML格式的,只能存放固定数据格式的对象
  • PList文件支持的数据格式有NSString, NSNumber, Boolean, NSDate, NSData, NSArray,和NSDictionary。其中,Boolean格式事实上以[NSNumber numberOfBool:YES/NO];这样的形式表示。NSNumber支持float和int两种格式。
  1. 创建文件路径
1
2
3
4
5
6
- (void)setUpPlist
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentDirectory = NSSearchPathForDirectorieInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];
self.filePath = [documentDirectory stringByAppendingPathComponent:@"test.plist"];
}
  1. 写入plist文件
1
2
3
4
5
6
7
8
9
- (void)saveData
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"textField"] = _textField.text;
if (![dict writeToFile:_path atomically:YES]) {
NSLog(@"Error!!!");
return;
}
}
  1. plist文件的读取
1
2
3
4
5
6
7
8
9
- (void)loadData
{
NSMutableDictionary *dict = [NSMutableDictionary
dictionaryWithContentsOfFile:_path];
NSString *content = dict[@"textField"];
 if (content && content.length > 0) {
_textField.text = content;
 }
}

Archiver&Unarchiver

>

  • NSUserDefaults和Plist文件支持常用数据类型,但是不支持自定义的数据对象
  • Cocoa提供了NSCoding和NSKeyArchiver两个工具类,可以把我们自定义的对象编码 成二进制数据流,然后存进文件里面
  1. NSCoding协议


1
2
3
4
5
6
7
8
9
10
11
//解档,解码。解档之后会生成一个该类的对象(解码后对模型的属性赋值)
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:kNameKey];
self.age = [aDecoder decodeIntForKey:kAgeKey];
self.studyID = [aDecoder decodeObjectForKey:kStudyIDKey];
}
return self;
}
1
2
3
4
5
6
7
8
9
10
11
//归档,编码 (将模型的属性编码)
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:kNameKey];
self.age = [aDecoder decodeIntForKey:kAgeKey];
self.studyID = [aDecoder decodeObjectForKey:kStudyIDKey];
}
return self;
}
----
  1. 保存数据
1
2
3
4
5
6
7
8
9
- (void)saveData{
_student = [[YMStudent alloc] init];
_student.name = _name.text;
_student.age = [_age.text intValue];
_student.studyID = _studyID.text;
if ([NSKeyedArchiver archiveRootObject:_student toFile:self.filePath]) {
 NSLog(@"Archive successfully!");
}
}
  1. 读取数据
1
2
3
4
5
6
7
8
9
- (void)loadData{
_student = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePAth];
if (student != nil) {
_name.text = student.name;
_age.text = [@(student.age) stringValue];
_studyID.text = student.studyID;
 NSLog(@"Archive successfully!");
}
}

SQLite

SQLite

SQLite shell command

SQLite shell command

SQLite usage

创建数据库连接对象: sqlite3

创建预编译语句对象:sqlite3_stmt

  1. 打开数据

    sqlite3_open()

  2. 将SQL语句转换为预编译语句对象

    sqlite3_prepare_v2()

  3. 执行预编译语句,每次处理一次,不需要返回值的语句(如INSERT,UPDATE,DELETE),只需要执行该函数即可

    sqlite3_step()

  4. 获取数据库中得不同类型的值

    • sqlite3_column_blob()
    • sqlite3_column_bytes()
    • sqlite3_column_bytes16()
    • sqlite3_column_count()
    • sqlite3_column_double()
    • sqlite3_column_int()
    • sqlite3_column_int64()
    • sqlite3_column_text()
    • sqlite3_column_text16()
    • sqlite3_column_type()
    • sqlite3_column_value()
  5. 销毁有sqlite3_prepare_v2()函数创建的预处理语句对象

    sqlite3_finalize()

  6. 关闭数据库(即销毁数据库连接对象)

    sqlite3_close()

    FMDB

    >

FMDB Document

Download FMDB

FMDB数据库操作类对sqlite3的操作进行了便利的封装并保证了多线程下的安全地操作数据库

FEMDB有三个主要的类
  1. FMDatabase - 表示一分单独的SQLite数据库,用来执行SQLite的命令
  2. FMResultSet - 表示FMDatabase执行查询结果集
  3. FMDatabaseQueue - 在多线程中执行多个查询或更新使用该类是线程安全的

数据库的创建

#define kDBFileName      @”database.sqlite”

NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];
NSString *DBPath = [docPath stringByAppendingPathComponent:kDBFileName];
FMDatabase *database = [FMDatabase databaseWithPath:DBPath];

打开数据库

if(![database open]){
    NSLog(@"Open database failed !");
    return;
}

执行更新

  • executeUpdate

一切不是SELECT命令的命令都是为更新。包括CREATE,UPDATE,INSERT,ALTER等。

执行结果返回一个BOOL值。YES表示成功,NO表示失败。可以调用 -lastErrorMessage和 -lastErrorCode方法获取更多的信息。

执行查询

  • executeQuery

执行结果返回FMResultSet对象,失败返回nil。同样可以调用-lastErrorMessage和 -lastErrorCode方法获取更多的信息。获得的FMResultSet对象rs后,既是只有一条记录,一样使用[rs next];

eg: FMResultSet *rs = [db executeQuery:@"SELECT Name, Age, FROM PersonList"];
while ([rs next]) {
    NSString *name = [rs stringForColumn:@"Name"];
    int age = [rs intForColumn:@"Age"];
}
FMResultSet根据类型提取数据
- objectForColumnName:
- longForColumn:
- nlongLongIntForColumn:
- boolForColumn:
- doubleForColumn:
- stringForColumn:
- dateForColumn:
- dataForColumn:
- dataNoCopyForColumn:
- UTF8StringForColumnName:


以上方法,都有个{type}ForColumnIndex:版本,根据column的位置提取数据

有些时候,只是需要query某一个row里特定的一个数值(比如只是要找John的年龄),FMDB 提供了几个比较简便的方法。这些方法定义在FMDatabaseAdditions.h,如果要使用,记得先 import进来

//找地址
NSString *address = [db stringForQuery:@"SELECT Address FROM PersonList WHERE Name = ?",@"John”];
NSString *address = [db stringForQuery:@"SELECT Address FROM PersonList WHERE Name = ?",@"John”];
//找年齡
int age = [db intForQuery:@"SELECT Age FROM PersonList WHERE Name     = ?",@"John”];

关闭数据库

  • [FMDatabase close];

数据库的批量操作

使用FMDatabase 的executeStatements:或者executeStatements:withResultBlock:(是否需 要返回结果)

NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"
"create table bulktest2 (id integer primary key autoincrement, y text);"
"create table bulktest3 (id integer primary key autoincrement, z text);"
"insert into bulktest1 (x) values ('XXX');"
"insert into bulktest2 (y) values ('YYY');"
"insert into bulktest3 (z) values ('ZZZ');";
success = [database executeStatements:sql];

或者

sql = @"select count(*) as count from bulktest1;"
}];
"select count(*) as count from bulktest2;"
"select count(*) as count from bulktest3;";
success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {
NSInteger count = [dictionary[@"count"] integerValue];
XCTAssertEqual(count, 1, @"expected one record for dictionary %@",
dictionary);
return 0;
}];

参数绑定

**INSERT INTO myTable VALUES (?, ?, ?)**    

问号只是占位,执行操作可以使用NSArray, NSDictionary, or a va_list来匹配参数
你也可以选择使用命名参数语法:INSERT INTO myTable VALUES (:id, :name, :value)
参数名必须以冒名开头。SQLite本身支持其他字符($,@),Dictionary key的内部实现是冒号 开头。注意你的NSDictionary key不要包含冒号

NSDictionary *argsDict = @{@"name":@"Jason"};
[db executeUpdate:@"INSERT INTO myTable VALUES (:name)"withParameterDictionary:argsDict];

FMDatabaseQueue 及线程安全

不能使⽤用同⼀个FMDatabase在不同线程中操作,多线程的操作是通过FMDatabaseQueue实现

首先创建队列,然后把单任务包装到事务里,串行执行

FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
[queue inDatabase:^(FMDatabase *db) {
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
FMResultSet *rs = [db executeQuery:@"select * from foo"];
while([rs next]) {
...
}

事务的回滚:(当前的队列的操作的取消)

[queue inTransaction:^(FMDatabase *db, BOOL *rollback) { 
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
if (whoopsSomethingWrongHappened) {
}
*rollback = YES;
return;
// etc...
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber
numberWithInt:4]];
}];

FMDatabaseQueue会在同一个队列里 同步执行任务, GCD也会按它接收的块的顺序来执行

关于Setting Bundles

>

  • Setting Bundle的概念更多地应该是在App的配置选择上
  • Setting Bundle可以给用户提供一个从《设置》应用里去配置应用程序的方式
  • 从开发者的角度来看,一般需要频繁修改的配置选项,如游戏的音量和控制选项等最好 放到app内部的设置页里,而类似于邮箱应用中的邮件地址和服务器的设置等不需要频 繁更改的配置项可以放到Setting Bundle里
  • 从《设置》应用中进行设置,实际上是操作iOS配置系统中的应用程序域(Application Domain),是持久的

iOS的配置系统中存在如下一些域,将来查询时严格按照如下列出域的顺序进行查找

Domain State
NSArgumentDomain volatile(易失的)
Application(Identified by the app’s identifier) persistent(持久的)
NSGlobalDomain persistent
Languages(Identified by the language names) volatile
NSRegisterationDomain volatile

registerDefaults:方法是在NSRegistrationDomain域上进行配置的,所以仅仅是存在于 内存中的,易失的

AFNetworking

下载AFNetworking开源代码

点击链接:AFNetworking

Architecture


NSURLConnection

  • AFURLConnectioinOperatioin
  • AFHTTPRequestOperation
  • AFHTTPRequestOperationManager

NSURLSession(iOS 7 /Mac OS 10.9)

  • AFURLSessionManager
  • AFHTTPSessionManager

Serialization

  • AFURLRequestSerialization

    • AFHTTPRequestSerialization

    • AFJSONRequestSerialization

    • AFPropertyListRequestSerialization

  • AFURLResponseSerialization

    • AFHTTPResponseSerialization

    • AFJSONResponseSerialization

    • AFXMLParserResponseSerialization

    • AFXMLDocumentResponseSerialization (MAC OS X)

    • AFPropertyListResponseSerialization

    • AFImageResponseSerializer

    • AFCompoundResponseSerializer

Additional Functionality

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

Usage

#define kBaseURL @”http://afnetworking.sinaapp.com


1
2
3
requestSerializer 默认是 [AFHTTPRequestSerializer serializer];
responseSerializer 默认是 [AFJSONResponseSerializer serializer];

AFHTTPRequestOperation

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_get.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:urlStr parameters:parameters error:nil];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc]initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
-----------------------------------------------------    
结果:
    Success:
    response object : {
        data =     {
            foo = bar;
        };
        success = 1;
    }
    Error:{
            "errors":"Parameter error!",
            "success":false
    }
-----------------------------------------------------    

AFHTTPRequestOperationManager

GET Request

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_get.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];
-----------------------------------------------------    
结果:
    Success: 
    response object : {
        data =     {
            foo = bar;
        };
        success = 1;
    }
    Error:{
            "errors":"Parameter error!",
            "success":false
    }
-----------------------------------------------------        

POST URL-Form-Request

NSString *httpUrlStr = [kBaseURL stringByAppendingPathComponent:@"request_post_body_http.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:httpUrlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];

NSString *jsonUrlStr = [kBaseURL stringByAppendingPathComponent:@"request_post_body_json.json"];
[manager POST:jsonUrlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];
-----------------------------------------------------    
结果:
    Success: 
    response object : {
        data =     {
            foo = bar;
        };
        success = 1;
    }
    Error:{
            "errors":"Parameter error!",
            "success":false
    }
-----------------------------------------------------

POST Multi-Part-Request

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"upload2server.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"b_Aquarius" withExtension:@"jpg"];
    [formData appendPartWithFileURL:fileURL name:@"image" fileName:@"constellation.jpg" mimeType:@"image/jpeg" error:nil];
    fileURL = [[NSBundle mainBundle] URLForResource:@"b_Aries" withExtension:@"png"];
    [formData appendPartWithFileURL:fileURL name:@"image" fileName:@"constellation.png" mimeType:@"image/png" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];
-----------------------------------------------------
结果:
    Success: 
    Response object : {
        data =     (
                    {
                name = "constellation.jpg";
                url = "http://afnetworking-userdomain.stor.sinaapp.com/constellation.jpg";
            },
                    {
                name = "constellation.png";
                url = "http://afnetworking-userdomain.stor.sinaapp.com/constellation.png";
            }
        );
        success = 1;
    }
-----------------------------------------------------

AFURLSessionManager

Creating a Download Task

/#define kDownloadUrl @”http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/346495/3464861417179661128.mp3?xcode=91aea20a92711d3d83f3f76a0952eb4b63b77ba183a87289&song_id=346486kDownloadUrl 是下载链接

NSURL *url = [NSURL URLWithString:kDownloadUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSString *filePath = @"/Users/qingyun/Desktop";
    NSString *newFielPath = [filePath stringByAppendingPathComponent:response.suggestedFilename];
    NSLog(@"name : %@",response.suggestedFilename);
    return [NSURL fileURLWithPath:newFielPath];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    if (error) {
        NSLog(@"Error : %@",error);
    }else{
        NSLog(@"File path : %@",filePath);
    }
}];
[downloadTask resume];
-----------------------------------------------------
结果:
Success: File path : file:///Users/qingyun/Desktop/Only%20Love.mp3
-----------------------------------------------------

Creation a Upload Task

    NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"upload2server.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSString *filePath = @"file:///Users/qingyun/Desktop/xml&json.pdf";
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:filePath] progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error : %@",error);
    }else{
        NSLog(@"Response objecct : %@",responseObject);
    }
}];
[uploadTask resume];
-----------------------------------------------------    
结果:
  Success:Response objecct : {
success = 1;
}
-----------------------------------------------------

Creation a Upload Task For Multi-Part Request, With Progress

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"upload2server.json"];
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"b_Cancer" withExtension:@"png"];
    [formData appendPartWithFileURL:fileURL name:@"image" fileName:@"Cancer.png" mimeType:@"image/png" error:nil];

    fileURL = [NSURL URLWithString:@"file://Users/qingyun/Desktop/xml&json.pdf"];
    [formData appendPartWithFileURL:fileURL name:@"image" error:nil];
} error:nil];
NSProgress *progress = nil;
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error : %@",error);
    }else{
        NSLog(@"Response objecct : %@",responseObject);
    }
}];
[uploadTask resume];
-----------------------------------------------------    
结果:
Success:Response objecct : {
        data =     (
                    {
                name = "Cancer.png";
                url = "http://afnetworking-userdomain.stor.sinaapp.com/Cancer.png";
            }
        );
        success = 1;
    }
-----------------------------------------------------

Creation a Data Task

NSURL *url = [NSURL URLWithString:[kBaseURL stringByAppendingPathComponent:@"response.json"]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error : %@",error);
    }else{
        NSLog(@"response object : %@",responseObject);
    }
}];
[dataTask resume];
-----------------------------------------------------
结果:
Success: response object : {
data = "This is a json data.";
success = 1;
}
-----------------------------------------------------

AFHTTPSessionManager

GET Request

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_get.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLSessionDataTask *dataTask = [manager GET:urlStr parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error : %@",error);
}];
[dataTask resume];
----------------------------------------------------
结果:
Success :response object : {
    data =     {
        foo = bar;
    };
    success = 1;
}
----------------------------------------------------

POSTRequest

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_post_body_http.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLSessionDataTask *dataTask = [manager POST:urlStr parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error : %@",error);
}];
[dataTask resume];
-----------------------------------------------------
结果:
Success:response object : {
    data =     {
        foo = bar;
    };
    success = 1;
}
-----------------------------------------------------

HEADRequest

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_post_body_http.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLSessionDataTask *dataTask = [manager HEAD:urlStr parameters:parameters success:^(NSURLSessionDataTask *task) {
    NSLog(@"Task : %@",task);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Task : %@ Error : %@",task,error);
}];
[dataTask resume];
----------------------------------------------------
结果:
Success: Task : <__NSCFLocalDataTask: 0x8d77b10> { completed }
----------------------------------------------------

AFNetworkReachabilityManager

/*
 *AFNetworkReachabilityStatusNotReachable     = 0,
 *AFNetworkReachabilityStatusReachableViaWWAN = 1,
 *AFNetworkReachabilityStatusReachableViaWiFi = 2
 */
NSArray *array = @[@"不可达",@"2G/3G/4G",@"wi-fi"];

[AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[self.manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"网络检测" message:[NSString stringWithFormat:@"%@",array[status]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];

}];

-----
[manager startMonitoring];
[manager stopMonitoring];

XML_JSON

XML

SAX解析

  1. 创建XML解析对象
1
2
NSURL *url = [NSBundle mainBundle] URLForResource:@"bookstore" withExternsion:@"xml"];
NSXMLParser *parser = [][NSXMLParser alloc]initWithContentsOfURL:url];
  1. 设置XMLParser 对象的delegate
1
parser.delegate = self;
  1. 调用delegate的fangf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
//当时开始解析的时候条用该方法,通常在这个方法里, 创建模型数组
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
//当开始解析,遇到元素的开始标签时,回调用这个方法,通常在这个方法里,创建模型对象,或解析标签中得属性并保存在模型对象中
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
//当解析到xml标签的文本内容时,回调用这个方法,通常在这个方法里,暂存解析到的文本内容
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
//当解析xml内容遇到结束标签时,回调用这个方法,通常在这个方法里,需要将模型对象保存到数组中或把标签对应的文本内容解析出来,保存在模型对象中。(通过KVC赋值)
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
//当整个xml解析完成条用这个方法,可以完成其他操作
}

DOM解析

以下以GDataXMLNode为例:

1
2
3
4
5
6
7
8
9
* <节点> (GDataXMLNode)
* 根据 DOM,XML ⽂文档中的每个成分都是⼀一个节点。
* DOM 是这样规定的:
* 整个⽂文档是⼀一个⽂文档节点
* 每个 XML 标签是⼀一个元素节点
* 包含在 XML 元素中的⽂文本是⽂文本节点
* 每⼀一个 XML 属性是⼀一个属性节点
* 注释属于注释节点

  1. 导入第三方库
1
2
3
4
5
导入第三方库时,首先编译检查是否可用,(头文件是否编译通过,头文件是否需要导入头文件路径,是否使用非ARC环境)
1. 头文件编译未通过,添加文件搜索路径,头文件为系统头文件时:在Build setting下的Header Search Paths 添加/usr/include/libxml2
头文件为用户头文件时:在Build setting下的User Header Search Paths 添加/usr/include/libxml2
2. 在Build Phases 下的Link Binary With Libraries 添加libxml2.dylib,链接的动态库
3. 在Build Phases 下的Compile Sources 将导入的编译文件设置为非ARC 即添加 -fno-objc-arc即可
  1. 创建GDataXMLDocument对象
1
2
NSData *data = [[NSBundle mainBundle] URLForResource:@"bokstore" withExternsion:"xml"];
GDataXMLDocument *document = [[GDataXMLDocument alloc]initWithData:data options:0 error:nil];
  1. 获取根元素rootElement
1
[document rootElement];
  1. 由根元素,可以获取到根元素下的子元素,以及对子元素的属性赋值;
1
2
3
4
5
6
获取子元素的方法:
- (NSArray *)elementsForName:(NSString *)name;
获取子元素属性的方法:
- (GDataXMLNode *)attributeForName:(NSString *)name;
将GDataXMLNode对象转换为NSString对象的方法:
- (NSString *)stringValue;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
for (GDataXMLElement *element in elements) {
// 创建图书对象
YMBook *book = [[YMBook alloc] init];
// 根据属性名字,解析book元素的属性值
book.category = [[element attributeForName:kCategory]
stringValue];
// 解析book的⼦子元素包含的⽂文本内容及其⼦子元素的属性
[0];
GDataXMLElement *titleElement = [element elementsForName:kTitle]
book.title = [titleElement stringValue];
book.lang = [[titleElement attributeForName:kLanguage]
stringValue];
GDataXMLElement *authorElement = [element
elementsForName:kAuthor][0];
book.author = [authorElement stringValue];
GDataXMLElement *yearElement = [element elementsForName:kYear]
[0];
book.year = [yearElement stringValue];
GDataXMLElement *priceElement = [element elementsForName:kPrice]
[0];
book.price = [priceElement stringValue];
 [_bookStore addObject:book];
}

JSON

1.数据分类
从结构上看,所有的数据(data)最终都可以分解成三种类型:

    - 第一种类型是标量(scalar),也就是一个单独的字符串(string)或数字 (numbers),比如"北京"这个单独的词 

    - 第二种类型是序列(sequence),也就是若干个相关的数据按照一定顺序并列在一 起,又叫做数组(array)或列表(List),比如"北京,上海" 

    - 第三种类型是映射(mapping),也就是一个名/值对(Name/value),即数据有一个 名称,还有一个与之相对应的值,这又称作散列(hash)或字典(dictionary),比 如"首都:北京"

Douglas Crockford发明了JSON,Json的规定非常简单:

  1. 并列的数据之间用逗号(“, “)分隔

  2. 映射用冒号(“: “)表示

  3. 并列数据的集合(数组)用方括号(“[]”)表示

  4. 映射的集合(对象)用大括号(“{}”)表示

比如,下面这句话:

“”北京市的⾯面积为16800平⽅方公⾥里,常住⼈人⼜⼝口1600万⼈人。上海市的⾯面积为6400平⽅方 公⾥里,常住⼈人⼜⼝口1800万。”

写成JSON格式就是这样:

1
2
3
4
[
 {"城市":"北京","⾯面积":16800,"⼈人⼝口":1600},
 {"城市":"上海","⾯面积
]

如果事先知道数据的结构,上面的写法还可以进一步简化:

1
2
3
4
[
["北京",16800,1600],
["上海",6400,1800]
]

NSJSONSerialization

1
2
3
4
5
6
7
8
9
10
- 反序列
+ (id)JSONObjectWithData:(NSData *)data
error:(NSError **)error
options:(NSJSONReadingOptions)opt
error:(NSError **)error
- 序列化
+ (NSData *)dataWithJSONObject:(id)obj
options:(NSJSONWritingOptions)opt


JSONKit

  1. 需要导入第三方库

使用: -fno-objc-arc

序列化: NSArray NSDictionary NSString

1
2
3
4
5
6
7
8
9
10
11
12
JSONData
– JSONDataWithOptions:includeQuotes:error:
-
JSONDataWithOptions:serializeUnsupportedClassesUsingDelegate:selector:error:
- JSONDataWithOptions:serializeUnsupportedClassesUsingBlock:error:
– JSONString
– JSONStringWithOptions:includeQuotes:error:
-
JSONStringWithOptions:serializeUnsupportedClassesUsingDelegate:selector:erro
r:
– JSONStringWithOptions:serializeUnsupportedClassesUsingBlock:error:

反序列化:NSData NSString

1
2
3
4
5
6
7
8
9
10
11
12
13
– objectFromJSONData
– objectFromJSONDataWithParseOptions:
– objectFromJSONDataWithParseOptions:error:
– mutableObjectFromJSONData
– mutableObjectFromJSONDataWithParseOptions:
– mutableObjectFromJSONDataWithParseOptions:error:
– objectFromJSONString
– objectFromJSONStringWithParseOptions:
– objectFromJSONStringWithParseOptions:error:
– mutableObjectFromJSONString
– mutableObjectFromJSONStringWithParseOptions:
– mutableObjectFromJSONStringWithParseOptions:error:


UIScrollView

ScrollView 不能滑动的常见原因

  1. contentsize 未设置
  2. scrollEnabled = NO;
  3. userInteractionEnabled = NO;
  4. 未取消autolayout

contentInset属性

控制scrollView四周可以多出的滑动长度,默认为四个参数均为0,急不可以滑动超出contentSize以外的区域

-(UIView )viewForZoomingInScrollView:(UIScrollView )scrollView;

该方法实现对返回的视图进行缩放大小,放回的视图必须是scrollView的子视图

diractionalLockEnabled

该属性设置为YES时可以控制在滑动scrollView时不会有晃动的效果,即当用户的滑动的方向不是正方向时,scrollView仍然只是针对某一个方向滑动

pagingEnable

该属性设置为YES时,可以控制用户滑动一下只翻一页。

UI_notes

image

UIView常用属性及方法

常用属性

NSInteger tag;

CGRect frame;

CGRect bounds;

CGPoint center;

CGAffineTransform transform;

BOOL multipleTouchEnable;

BOOL exclusiveTouch;

UIView *superView;

NSArray *subViews;

UIWindow *window;

UIColor *backgroundColor;

CGFloat alpa;

BOOL opaque;

BOOL hidden;

常用方法

类方法

1
+ (id)initWithFrame:(CGRect)frame;

实例方法

1
2
3
4
5
6
- (void)removeFromSuperview;
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;
- (void)addSubview:(UIView *)view;
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;

UIView常见子类

UIControl

常用属性

BOOL enable;

BOOL selected;

BOOL highlighted;

UIControlState state;<readonly>

BOOL touchInside;<readonly>

实例方法

1
2
3
4
- (void)addTarget:(id)target action:(SEL)action forControlEvent:(UIControlEvent)controlEvent;
- (void)removeTarget:(id)target action:(SEL)action forControlEvent:(UIControlEvent)controlEvent;
- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent)event;
- (void)sendActionsForControlEvents:(UIControlEvent)controlEvents;

UIControl常见子类

UIButton

常用属性

UIButtonType buttonType;<readonly>

NSString *currentTitle;<readonly>

UIColor *currentColor;<readonly>

UIImage *currentImage;<readonly>

UIImage *currentBackgroundImage;<readonly>

NSAttributedString *currentAttributedTitle;<readonly>

类方法

1
+ (id)buttonWithType:(UIButtonType)buttonType;

实例方法

1
2
3
4
5
6
7
8
9
10
- (void)setTitle:(NSString *)title forState:(UIControlState)state;
- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state;
- (void)setImage:(UIImage *)image forState:(UIControlState)state;
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;
- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state;
- (NSString *)titleForState:(UIControlState)state;
- (UIColor *)titleColorForState:(UIControlState)state;
- (UIImage *)imageForState:(UIControlState)state;
- (UIImage *)backgroundImageForState:(UIControlState)state;
- (NSAttributedString *)attributedStringForState:(UIControlState)state;

UISlider

常见属性

float value;

float minimumValue;

float maximumValue;

UIImage *minimumValue;

UIImage *maximumValue;

BOOL continuous;

UIColor *minimumTrackTintColor;

UIColor *maximumTrackTintColor;

UIColor *thumbTintColor;

readonly

UIImage *currentThumbImage;

UIImage *currentMinimumTrackImage;

UIImage *currentMaximumTrackImage;

实例方法

1
2
3
4
5
6
- (void)setThumbImage:(UIImage *)image forState:(UIControlState)state;
- (void)setMinimumTrackImage:(UIImage *)image forState:(UIControlState)state;
- (void)setMaximumTrackImage:(UIImage *)image forState:(UIControlState)state;
- (UIImage *)thumbImage forState:(UIControlState)state;
- (UIImage *)minimumTrackImage forState:(UIControlState)state;
- (UIImage *)maximumTrackImage forState:(UIControlState)state;

UITextField

常用属性

NSString *text;

UIColor *textColor;

UIFont *font;

NSTextAlignment textAlignment;

UITextBorderStyle borderStyle;

NSString *placeholder;

BOOL clearOnBeginEditing;

BOOL adjustsFontSizeToFitWidth;

CGFloat minimumFontSize;

id delegate;

UIImage *background;

UIImage *disabledBackground;

BOOL editing;

UITextFieldViewMode clearButtonMode;

UIView *leftView;

UITextFieldViewMode leftViewMode;

UIView *rightView;

UITextFieldViewMode rightViewMode;

UIView *inputView;

UIView *inputAccessoryView;

实例方法

1
2
- (void)drawPlaceholderInRect:(CGRect)rect;
- (void)drawTextInRect:(CGRect)rect;

UISegmentedControl

常用属性

UISegmentedControlStyle segmentedControlStyle;

NSUInteger numberOfSegments; <readonly>

UIColor *tintColor;

NSInteger selectedSegmentIndex;

实例方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (id)initWithItems:(NSArray *)items;
- (void)insertSegmentWithTitle:(NSString *)title atIndex:(NSUInteger)segment animated:(BOOL)animated;
- (void)insertSegmentWithImage:(UIImage *)image atIndex:(NSUInteger)segment animated:(BOOL)animated;
- (void)removeSegmentAtIndex:(NSUInteger)segment animated:(BOOL)animated;
- (void)removeAllSegments;
- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)segment;
- (NSString *)titleForSegmentAtIndex:(NSUInteger)segment;
- (void)setImage:(UIImage *)image forSegmentAtIndex:(NSUInteger)segment;
- (UIImage *)imageForSegmentAtIndex:(NSUInteger)segment;
- (void)setWidth:(CGFloat)width forSegmentAtIndex:(NSUInteger)segment;
- (CGFloat)widthForSegmentAtIndex:(NSUInteger)segment;
- (void)setEnabled:(BOOL)enabled forSegmentAtIndex:(NSUInteger)segment;
- (BOOL)isEnabledForSegmentAtIndex:(NSUInteger)segment;
- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics;
- (UIImage *)backgroundImageForState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics;

UIPageControl

常用属性

NSInteger numberOfPages;

NSInteger currentPage;

BOOL hidesForSinglePage;

BOOL defersCurrentPageDisplay; //点击翻页无效

UIColor *pageIndicatorTintColor;

UIColor *currentPageIndicatorColor;

实例方法

1
2
- (void)updateCurrentPageDisplay;
- (CGSize)sizeForNumberOfPages:(NSInteger)pageCount;

UISwitch

常用属性

UIColor *onTintColor;

UIColor *tintColor;

UIColor *thumbColor;

UIImage *onImage;

UIImage *offImage;

BOOL on;

实例方法

1
2
- (void)initWithFrame:(CGRect)frame;
- (void)setOn:(BOOL)on animated:(BOOL)animated;

UIDatePicker

常用属性

UIDatePicker datePickerMode;

NSLocale *locale;

NSTimeZone *timeZone;

NSDate *date;

NSDate *minimumDate;

NSDate *MaximumDate;

NSTimerInterval *countDownDuration;

NSInteger minuteInterval;

实例方法

1
- (void)setDate:(NSDate *)date animated:(BOOL)animated;

UILabel

常用属性

NSString *text;

UIFont *font;

UIColor *color;

UIColor *shadowColor;

CGSize shadowOffset;

NSTextAlignment textAlignment;

NSLineBreakMode lineBreakMode;

NSAttributedString attributedText;

UIColor *highlightedTextColor;

BOOL highlighted;

BOOL userInteractionEnabled;

BOOL enabled;

NSInteger numberOfLines;

BOOL adjustsFontSizeToFitWidth;

BOOL minimumFontSize;

实例方法

1
2
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines;
- (void)drawTextInRect:(CGRect)rect;

UIAlertView

常见属性

id delegate;

NSString *title;

NSString *message;

NSInteger cancelButtonIndex;

readonly

NSInteger numberOfButtons;

NSInteger firstOtherButtonIndex;

BOOL visible;

UIAlertViewStyle alertViewStyle;

实例方法

1
2
3
4
- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id /*<UIAlertViewDelegate>*/)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... ;
- (void)show;
- (void)dismissWithClickEdButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated;
- (UITextField *)textFieldAtIndex:(NSInteger)textFieldIndex;

UIActionSheet

常见属性

id delegate;

NSString *title;

UIActionSheetStyle actionSheetStyle;

NSInteger cancelButtonIndex;

NSInteger destructiveButtonIndex;

readonly

NSInteger numberOfButtons;

NSInteger firstOtherButtonIndex;

BOOL visible;

实例方法

1
2
3
4
5
6
7
8
9
- (id)initWithTitle:(NSString *)title delegate:(id<UIActionSheetDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... ;
- (NSInteger)addButtonWithTitle:(NSString *)title;
- (NSString *)buttonTitleAtIndex:(NSInteger)buttonIndex;
- (void)showFromToolbar:(UIToolBar *)view;
- (void)showFromTabBar:(UITabBar *)view;
- (void)showFromBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animates;
- (void)showFromRect:(CGRect)rect inView:(UIView *)view animated:(BOOL)animated;
- (void)showInView:(UIView *)view;
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated;

UIImageView

常用属性

UIImage *image;

UIImage *highlightedImage;

BOOL userInteractionEnable;

BOOL highlighted;

NSArray *animationImages;

NSArray *highlightedAnimationImages;

NSTimeInterval animationDuration;

NSInteger animationRepeatCount;

UIColor tintColor;

实例方法

1
2
3
4
5
- (id)initWithImage:(UIImage *)image;
- (id)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage;
- (void)startAnimating;
- (void)stopAnimating;
- (BOOL)isAnimating;

UINavigationBar

常用属性

UIBarStyle barStyle;

id delegate;

BOOL translucent;

NSArray *items;

UIColor *tintColor;

UIColor *barTintColor;

UIImage *shadowImage;

NSDictionary *titleTextAttributes;

UIImage *backIndicatorImage;

UIImage *backIndicatorTransitionMaskImage;

readonly

UINavigationItem *topItem;

UINavigationItem *backItem;

实例方法

1
2
3
4
5
6
7
8
9
- (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animated;
- (UINavigationItem *)popNavigationItemAnimated:(BOOL)animated;
- (void)setItems:(NSArray *)items animated:(BOOL)animated;
- (void)setBackgroundImage:(UIImage *)backgroundImage forBarPosition:(UIBarPosition)barPosition barMetrics:(UIBarMetrics)barMetrics;
- (UIImage *)backgroundImageForBarPosition:(UIBarPosition)barPosition barMetrics:(UIBarMetrics)barMetrics;
- (void)setBackgroundImage:(UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0);
- (UIImage *)backgroundImageForBarMetrics:(UIBarMetrics)barMetrics;
- (void)setTitleVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics;
- (CGFloat)titleVerticalPositionAdjustmentForBarMetrics:(UIBarMetrics)barMetrics;

UITabBar

常用属性

id delegate;

NSArray *items;

UIBarStyle barStyle

UITabBarItem *selectedItem;

UIColor *tintColor;

UIColor *barTintColor;

BOOL translucent;

UIColor *selectedImageTintColor;

UIImage *backgroundImage;

UIImage *selectionIndicatorImage;

UIImage *shadowImage;

UITabBarItemPositioning itemPositioning;

CGFloat itemWidth;

CGFloat itemSpacing;

实例方法

1
2
3
4
- (void)setItems:(NSArray *)items animated:(BOOL)animated;
- (void)beginCustomizingItems:(NSArray *)items;
- (BOOL)endCustomizingAnimated:(BOOL)animated;
- (BOOL)isCustomizing;

UIToolbar

常用属性

UIBarStyle barStyle;

NSArray *items;

BOOL translucent;

UIColor *tintColor;

UIColor *barTintColor;

id delegate;

实例方法

1
2
3
4
5
- (void)setItems:(NSArray *)items animated:(BOOL)animated;
- (void)setBackgroundImage:(UIImage *)backgroundImage forToolbarPosition:(UIBarPosition)topOrBottom barMetrics:(UIBarMetrics)barMetrics;
- (UIImage *)backgroundImageForToolbarPosition:(UIBarPosition)topOrBottom barMetrics:(UIBarMetrics)barMetrics;
- (void)setShadowImage:(UIImage *)shadowImage forToolbarPosition:(UIBarPosition)topOrBottom;
- (UIImage *)shadowImageForToolbarPosition:(UIBarPosition)topOrBottom;

UISearchBar

常用属性

UIBarStyle barStyle;

id delegate;

NSString *text;

NSString *prompt;

NSString *placeholder;

BOOL showsBookmarkButton;

BOOL showsCancelButton;

BOOL showsSearchResultsButton;

UIColor *tintColor;

UIColor *barTintColor;

UISearchBarStyle searchBarStyle;

UITextAutocapitalizationType autocapitalizationType;

UITextAutocorrectionType autocorrectionType;

UITextSpellCheckingType spellCheckingType;

UIKeyboardType keyboardType;

NSArray *scopeButtonTitles;

NSInteger selectedScopeButtonIndex;

BOOL showsScopeBar;

UIView *inputAccessoryView;

UIWebView

常用属性

id delegate;

readonly

BOOL canGoBack;

BOOL canGoForward;

BOOL loading;

UIScrollView *scrollView;

NSURLRequest *request;

实例方法

1
2
3
4
5
6
7
8
- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
- (void)reload;
- (void)stopLoading;
- (void)goBack;
- (void)goForward;
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

UIPickerView

常用属性

id dataSource;

id delegate;

BOOL showsSelectionIndicator;

NSInteger numberOfComponents;<readonly>

实例方法

1
2
3
4
5
6
7
- (NSInteger)numberOfRowsInComponent:(NSInteger)component;
- (CGSize)rowSizeForComponent:(NSInteger)component;
- (UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component;
- (void)reloadAllComponents;
- (void)reloadComponent:(NSInteger)component;
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated;
- (NSInteger)selectedRowInComponent:(NSInteger)component;

UITableViewCell

常用属性

UITableViewStyle style; <readonly>

id dataSource;

id delegate;

CGFloat rowHeight;

CGFloat sectionHeaderHeight;

CGFloat sectionFooterHeight;

CGFloat estimatedRowHeight;

CGFloat estimatedSectionHeaderHeight;

CGFloat estimatedSectionFooterHeight;

UIEdgeInsets separatorInset;

UIView *backgroundView;

BOOL editing;

BOOL allowsSelection;

BOOL allowsSelectionDuringEditing;

BOOL allowsMultipleSelection;

BOOL allowsMultipleSelectionDuringEditing;

UIView *tableHeaderView;

UIView *tableFooterView;

NSInteger sectionIndexMinimumDisplayRowCount;

UIColor *sectionIndexColor;

UIColor *sectionIndexBackgroundColor;

UIColor *sectionIndexTrackingBackgroundColor;

UITableViewCellSeparatorStyle separatorStyle;

UIColor *separatorColor;

实例方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style;
- (void)reloadData;
- (void)reloadSectionIndexTitles;
- (NSInteger)numberOfSections;
- (NSInteger)numberOfRowsInSection:(NSInteger)section;
- (CGRect)rectForSection:(NSInteger)section;
- (CGRect)rectForHeaderInSection:(NSInteger)section;
- (CGRect)rectForFooterInSection:(NSInteger)section;
- (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point;
- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell;
- (NSArray *)indexPathsForRowsInRect:(CGRect)rect;
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSArray *)visibleCells;
- (NSArray *)indexPathsForVisibleRows;
- (UITableViewHeaderFooterView *)headerViewForSection:(NSInteger)section;
- (UITableViewHeaderFooterView *)footerViewForSection:(NSInteger)section;
- (void)beginUpdates;
- (void)endUpdates;
- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)moveSection:(NSInteger)section toSection:(NSInteger)newSection;
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)moveRowAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath;
- (NSIndexPath *)indexPathForSelectedRow;
- (NSArray *)indexPathsForSelectedRows;
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier;
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;
- (id)dequeueReusableHeaderFooterViewWithIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier;
- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forHeaderFooterViewReuseIdentifier:(NSString *)identifier;
- (void)registerClass:(Class)aClass forHeaderFooterViewReuseIdentifier:(NSString *)identifier;

UIViewController

常用属性

UIView *view;

NSString *title;

readonly

NSString *nibName;

NSBundle *nibBundle;

UIStoryboard *storyboard;

UIViewController *parentViewController;

UIViewController *presentedViewController;

UIViewController *presentingViewController

实例方法

1
- (void)loadView;

UIViewController的常见子类

UITabBarController

常用属性

NSArray *viewControllers;

UIViewController *selectedViewController;

NSUInteger selectedIndex;

id delegate;

readonly

UITabBar *tabBar;

UINavigationController *moreNavigationController;

实例方法

1
- (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated;

UINavigationController

常用属性

id delegate;

NSArray *viewControllers;

BOOL toolbarHidden;

readonly

UIViewController *topViewController;

UIViewController *visibleViewController;

UINavigationBar *navigationBar;

UIToolbar toolbar;

实例方法

1
2
3
4
5
6
7
8
- (id)initWithRootViewController:(UIViewController *)rootViewController;
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (UIViewController *)popViewControllerAnimated:(BOOL)animated;
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated;
- (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated;
- (void)setNavigationBarHidden:(BOOL)hidden animated:(BOOL)animated;
- (void)setToolbarHidden:(BOOL)hidden animated:(BOOL)animated;

UITableViewController

常用属性

UITableView *tableView;

BOOL clearsSelectionOnViewWillAppear;

UIRefreshControl *refreshControl;

实例方法

1
- (id)initWithStyle:(UITableViewStyle)style;

UIBarItem

常用属性

BOOL enable;

NSString *title;

UIImage *image;

UIImage *landscapeImagePhone;

UIEdgeInsets imageInsets;

UIEdgeInsets landscapeImagePhoneInsets;

NSInteger tag;

实例方法

1
2
- (void)setTitleTextAttributes:(NSDictionary *)attributes forState:(UIControlState)state;
- (NSDictionary *)titleTextAttributesForState:(UIControlState)state;

UIBarButtonItem

常用属性

UIBarButtonItem style;

CGFloat width;

NSSet *possibleTitles;

UIView *customView;

SEL action;

id target;

实例方法

1
2
3
4
5
6
7
- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action;
- (id)initWithImage:(UIImage *)image landscapeImagePhone:(UIImage *)landscapeImagePhone style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action;
- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action;
- (id)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action;
- (id)initWithCustomView:(UIView *)customView;
- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics;
- (UIImage *)backgroundImageForState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics

UITabBarItem

常用属性

UIImage selectedImage;

NSString badgeValue;

实例方法

1
2
3
- (id)initWithTitle:(NSString *)title image:(UIImage *)image tag:(NSInteger)tag;
- (instancetype)initWithTitle:(NSString *)title image:(UIImage *)image selectedImage:(UIImage *)selectedImage NS_AVAILABLE_IOS(7_0);
- (id)initWithTabBarSystemItem:(UITabBarSystemItem)systemItem tag:(NSInteger)tag;

UINavigationItem

常用属性

NSSting *title;

UIBarButtonItem *backBarButtonItem;

UIView *titleView;

NSString *prompt;

BOOL hidesBackButton;

NSArray *leftBarButtonItems;

NSArray *rightBarButtonItems;

BOOL leftItemsSupplementBackButton;

UIBarButtonItem *leftBarButtonItem;

UIBarButtonItem *rightBarButtonItem;

实例方法

1
2
3
4
5
6
- (id)initWithTitle:(NSString *)title;
- (void)setHidesBackButton:(BOOL)hidesBackButton animated:(BOOL)animated;
- (void)setLeftBarButtonItems:(NSArray *)items animated:(BOOL)animated;
- (void)setRightBarButtonItems:(NSArray *)items animated:(BOOL)animated;
- (void)setLeftBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated;
- (void)setRightBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated;

c-notes

image

间接 标准 统一 机制 策略

iTerm 的配置

  1. 将iTerm移到应用程序

    进入配置文件

1
$ cd iterm$zsh/.oh my zsh/templates
  1. ls 查看当前目录下的所有文件

    拷贝当前目录下的文件 zshrc.zsh-template 到~/.zshrc 下

1
$ cp zshrc.zsh-template
  1. 退出iterm,重启即可
1
$ q

VI编辑器中的基本命令

VI编辑器中的基本内部命令

在终端使用 vimtutor 命令可以查看VI编辑器中的基本命令

  1. 复制命令

    复制单个字符: y

    复制一个单词: yw

    复制所选中的一行: yy

  2. 移动命令
    移动光标到行首: ^

    向前移动一个单词: b

    向后移动一个单词: w

    向下翻一页: ctrl + f

    向上翻一页: ctrl + b

  3. d + ^ 删除光标所在位置到行首的所有字符

  4. d + $ 删除光标所在位置到行尾的所有字符
VI编辑器中的基本外部命令
  1. 删除命令

     * rm [filename] 删除基本文件
     * rm -r [filename] 有提示的删除一个文件夹
     * rm -rf [filename] 强制删除文件夹,包括文件夹内的所有子文件夹以及自文件,且无提示 
      * rm \*~   (*为通配符),即删除所有以~结尾的文件
    
  2. 拷贝命令

     * 若file2文件家不存在,默认将file1 拷贝一分命名为file2 
     * 若file2时文件夹,默认将file1拷贝到文件夹file2下,且名字仍为file1 
     * file1 file2 不加路径的情况下,默认是把当前路径下的文件拷贝到当前路径下 
     * ile1 file2 表示为路径的形式,则是把指定路径下的file1 拷贝到指定路径下命名为file2,或是拷贝到制定路径下的file2文件夹下命名仍然是file1 
     * cp -r/R [file1][file2] 
     * 将文件夹1拷贝到文件夹2目录下 
    
  3. 重命名(移动命令)

    mv [file1][file2]

    • 若两文件在同一路径下且file2文件家不存在,默认将file1 重命名为file2
    • 若file2时文件夹,默认将file1移动到文件夹file2下,且名字仍为file1
      • file1 file2 不加路径的情况下,默认是把当前路径下的文件重命名为file2
    • file1 file2 表示为路径的形式,则是把指定路径下的file1 移动到指定路径下命名为file2,或是移动到指定路径下的file2文件夹下命名仍然是file1
  4. 其他命令

    • ls -a列出当前目录下的所有文件及文件夹,包括隐藏文件(以 “.” 开始的文件或文件夹)其中 . 和 ..两个文件夹表示是当前路径和上级路径
    • cd 切换路径
    • du -h [filename] 默认为查看当前路径下人类可读的文件的大小,追加filename,则是查看该文件夹下的人类可读的文件的大小
    • diff [file1][file2]比较两个文件内容是否相同,相同的话无显示结果;不同的话,则列出不同之处
    • file [file] 查看该文件的类型(如二进制类型,ASCII,English等)
    • !!调出上次使用的命令
      ! + 使用过的命令的首字母后第一个单词,调出最近使用过包含该字母或单词的命令
      ctrl + r 搜索使用过的命令
      ctrl + c 结束当前输入的命令,即不执行当前输入的命令
    • gcc 执行命令时 加-g 可进行调试 (l 列出函数的源代码,b 设置断点,r 运行程序,n 执行下一步,s 进入函数内部,p [var] 打印变量var的值 q 退出程序 ), 加 -save-temps 保留编译时生成的结果(即 .i, .s, .o 文件生成且被保留下来可供查看)
    • $?(echo $? 在屏幕上显示上次命令执行的结果,若执行成功则返回0,否则返回1;若上次执行是程序且执行成功则返回return 后的返回值)
      echo $HOME 显示当前的home路径
      echo $USER 显示当前的用户名
    • cat [filename] | head 查看文件的前十行内容

      注释方法

    • // 注释一行
    • 注释多行

      1. /*…*/
      2. #if 0

        #else

        #endif

        注释从 if 0 到else之间的多行,程序在编译,只编译else与endif之间的多行;若果把0换成非零值,则只

    • 头文件的保护

      #ifndef [宏名]

      #define [宏名]

      #endif

      在引用头文件时,如果未定义头文件内已定义过的内容,则定义;否则,不再重复定义

变量的作用范围

  1. 函数作用域 仅限在一个函数中使用
  2. 文件作用域 仅限在一个文件中使用
  3. 代码快作用域 受限与“ {}” 的限制
  4. 原型作用域 函数声明

变量的大小

  1. char c 语言标准规定为1字节
  2. int 一般为4字节 规定int的大小不超过long的大小,short的大小不超过int的大小
  3. 指针的大小与long的大小等于机器字长(即 32位os 其大小为4字节,64的os其大小为8字节),古可用sizeof(int)测试机器os时多少位的(sizeof只是一个操作符,并不是一个函数)。

数据类型

  • 整型:char short int long
  • 浮点型: float double
  • 指针
  • 聚合类型:数组,结构体,枚举类型
  • 派生类型:字符串,联合体

    赋值操作 值得注意点

  • 数组名是个地址,只能在初始化是对其赋值,在以后使用中,数组名是个地址常量,不能被作为左值对其赋值
  • 对字符数组初始化赋值为字符串字面常量,相当于把全局数据段的字符串复制到栈对字符数组分配的地址中去。
  • 指针是指针变量可以对其进行赋值运算
  • 结构体类型的变量可以作为左值对其进行赋值

分配内存问题

  • 在函数中定义变量,对其分配内存时不能太大
  • 可使用全局变量在全局数据段分配大内存
  • 可使用malloc(size)动态在堆中分配大内存,使用memset将申请的内存初始化。

字符串操作中段错误

  • 定义一个指向NULL地址的字符串指针
    NULL的ascii值为0,地址为0的内存不可以被访问,故对该地址进行写操作是没有权限的。
  • 在定义一个字符串数组时对其进行初始化为字符串字面常量
    对字符串数组定义并初始化为一个字符串字面常量时,字符数组首地址指向的是全局数据段的地址,对该段内存进行写操作是没有全县的。
  • 使用strcpy,strcat,strcmp,strcasecmp等字符串操作函数,将目标字符串读/写爆。应该使用strncpy,strncat,strncmp,strncasecmp等字符串操作函数防止读写越界。

文件操作常用函数

  1. 字符读写 fgetc(FILE *fp);
1
fputc(int c,FILE*fp);
  1. 按行读写 fgets(char str,size,FILE \fp);
1
fputs(char \*,size,FILE *fp);
  1. 数据块读写 fread(char *,size,number,FILE *fp);
1
fwrite(char \*, size,number,FILE \*fp);
  1. 格式化读写 fprintf(FILE *fp,format,…);
1
fsanf(FILE *fp,format,...);
三种缓冲机制
  • 行缓冲 缓冲区存储一行信息才进行输出 eg:stdout(标准输出)
  • 全缓冲 缓冲区存储满信息才进行输出
  • 无缓冲 缓冲区只要有信息存储进去就进行输出 eg:stderr(报错)
    改变文件指针位置
    • rewind(FILE *fp); 改变指针指向头文件
    • fseek(FILE *fp,int length,long where);(where 可取值为SEEK_SET SEEK_CUR SEEK_END) 改变指针位置从(文件头部,当前位置,文件尾部)移动length个字节的位置

image

git-base-operation

image

基本操作

创建一个裸仓库

git init --bare

初始化基本仓库

git init

配置作者信息

1
2
git config --global user.name "liufengxia"
git config --global usr.emil 1874962073@163.com

添加文件到暂存区(跟踪文件)

git add [filename]

git add * // 跟踪所有已跟踪过又修改的文件

移除文件

git rm [filename]

重命名一个文件

git mv [oldname] [newname]

提交暂存区

git commit -m "description information"// git commmit 只提交在暂存区的内容

git commit -a -m "description information"// 将跟踪过又修改的为放入暂存跟踪后直接提交,已放入暂存区的也直接一起提交

查看工作目录的状态

git status

查看提交历史记录

git log

查看文件改变

git diff //默认比较工作区下的文件与最近一次提交的不同

git diff -- stash//比较暂存区下的文件与最近一次提交的不同

撤销操作

撤销加入暂存区的操作

git reset -- [filename]

撤销修改的操作

git checkout -- [filename]

将本地的修改放进回收站

git stash

从回收站中恢复本地的修改

git stash apply

Tag操作

查看tag

git tag

创建tag

git tag -a tagname -m "tag description information"

显示tag信息

git show tagname

对之前的提交打tag

git tag -a tagname -m "tag description information" commit-num

分支操作

查看分支

// 默认查看本地分支

git branch

// 查看本地以及远端分支

git branch -a

// 查看远端分支

git branch -r

创建分支

git branch newbranchname

删除分支

git branch -d/D branchname

切换分支

git checkout branchname

创建分支并切换到新建的分支下

git branch checkout -b newbranch

合并分支

git merge branchname branchname

rebase操作

git rebase branchname branchname

远端仓库操作

克隆一个远端仓库

git clone URL/repodirectory

添加远端仓库

git remote add reponame URL/repodirectory

更新远端仓库的分支和数据

git fetch //默认更新远端master分支

git fetch reponame branchname //更新指定远端的分支

获取并合并远端仓库的分支到当前分支

git pull reponame branchname

eg: git pull origin master

上传本地分支和数据到远端仓库

git push reponame branchname

eg: git push origin master

跟踪远端仓库上的分支

git checkout —track origin/testbranch

git checkout -b test origin/testbranch

setUpBlog

image

安装brew

执行命令

1
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

安装wget

执行命令

1
$ brew install wget

安装nvm(node.js的版本管理工具)

1
$ wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh

添加如下内容到~/.zshrc 配置文件

1
[ -s "/Users/`users`/.nvm/nvm.sh" ] && . "/Users/`users`/.nvm/nvm.sh" # This loads nvm

安装node.js(通过nvm安装)

1
$ nvm install 0.10

安装hexo

1
$ npm install -g hexo

创建hexo文件夹,并安装hexo组件

1
2
3
$ hexo init hexo
$ cd hexo
$ npm install

查看本地

输⼊入如下命令后,打开浏览器,并输⼊入localhost:4000来查看

1
2
$ hexo g
$ hexo s

登录github.com注册github账号

创建与github同名的repository

eg : github账号名位lfxfengxia,则创建lfxfengxia.github.io

部署到github上

如下所示编辑_config.yml

1
2
3
4
deploy:
type: github
repository: git@github.com:dorayox/dorayox.github.io.git
branch: master

输入如下命令,完成到github的部署,之后打开浏览器并输入dorayox.github.io来查看

1
2
$ hexo g
$ hexo d

上传文件到blog

在hexo目录下,创建新文件

eg : 创建新文件test

1
$ hexo new test

默认创建的新文件后缀问 .md文件,存在hexo/source/_posts/目录下

使用MOU打开新建的文件并完成编辑

1
$ mou source/_posts/test.md

将新建的文件声称网页

1
$ hexo g

上传到blog

1
$ hexo d

登录blog查看是否上传成功

http://lfxfengxia.github.io

image

image

NSLog 与 printf的不同

1. NSLog接收oc字符串作为参数,printf接收c语言的字符串作为参数
2. NSLog输出后会自动换行,printf在输出后不会自动换行
3. 使用NSLog时,需要包含头文件#import <Foundition/Foundition.h>;而使用printf时,需要包含头文件#include<stdio.h>
4. NSLog可以输出日期,时间戳,进程号等信息,而printf不能输出这些信息

常用术语

面向过程 : Procedure Oriented

面向对象 : Object Oriented ,简称OO

面向编程 : Object Oriented Programming,简称OOP

OC 语法

  1. 类的声明
    @interface 类名:父类(默认为 NSObject 该类时根类)

    {

        定义成员变量;(默认情况下,成员变量为protect类型,)

    }    

    ( 可以用@public将其定义为public类型,此时定义的属性或变量允许被外界访问)
    @property(nonatomic/atomic,readonly/readwrite,assign/strong/retain/wake)类型 属性名;(定义属性可以自动生成setter和getter方法)

    声明类方法;(标识 + 该方法向类发消息)

    声明实例方法; (标识 - 该方法向对象发消息) 声明类方法时 返回值最好定义为`instancetype`类型

    @end
  1. 类的实现

     @implemention 类名
    
     - 实例方法
    {
            实现代码; 
     }
    
     + 类fangfa
    { 
            实现代码; 
     }
    
     重写父类方法;
     如:descripition、 dealloc、init等
    
     @end
    

    3.创建对象

     1.包含所创建类的头文件
     2.类名 *对象名;
     2.1 类名 *对象名 = [[类名 alloc]init];(创建对象并为其分配内存、初始化)
     2.2 类名 *对象名 = [类名 new];(每次都会创建出新的对象,并且返回对象的地址。)
     3. 给对象赋值;(可以调用相应的类方法);
     4. 给对象发消息,完成所需要进行的操作;[对象 方法];
    
  2. 匿名对象

        方法调用:
    
            [[类名 new]方法];/[[[类名 alloc]init]方法];
    
        属性访问:
    
            [类名 new->属性 = 赋值;(外界访问定义为public类型的属性)
    

OC方法和函数的区别

1. OC方法的声明只能在@interface@end之间,只能在@implementation@end之间。即OC方法独立于类存在。
2. C函数不属于类,跟类没有联系,C函数所有权只属于定义函数的文件
3. C函数不能访问OC对象的成员变量。

OC语法细节

1. 成员变量不能在{}中进行初始化、不能直接拿去访问
2. 方法的声明不能写在@end之后
3. 方法不能当作函数一样调用
4. 成员变量、方法不能用static等关键字进行修饰

OC方法注意点

方法只有声明,没有实现(经典错误,系统提示警告)
方法没有声明,只有实现(编译器警告,但是可以调用,OC的弱语法)
编译的时候,访问没有定义的成员变量直接报错,调用没有的方法,只是警告
没有@interface,纸偶@implemenation也可以成功定义一个类
        @implemenation Dog : NSObject
        {
            int _age;
            NSString *_name;
        }

        - (void)print
        {
            NSLog(@"The dog's name is %@,ang de it's %d years old!",_name,_age);
        }
        @end

@implemenation 中不能声明和@interface一样的成员变量

OC中有`BOOL`基本数据类型,其值是`YES`和`NO`,而不是truefalse,它实际上是一种对带符号的自负类型(signed char)的定义(typedef),它使用8为存储空间。`YES定义为1NO定义为0`;

image

类方法he实例方法

  1. 类方法

     * 该方法是直接可以用类名来执行的方法(类本身会在内存中占据存储空间,里面有类/对象方法列表)
     * 以加号 + 开头
     * 只能用类名调用,对象不能调用
     * 类方法不能访问实例变量(成员变量)
     * 使用场合:当不需要访问成员变量时,尽量使用类方法
     * 类方法和对象方法可以同名
    
  2. 实例方法

     * 该方法是用对象名来执行的方法
     * 以减号 — 开头
     * 只能用对象名调用,类不能调用,该方法没有对象是不能被执行的
     * 对象方法能访问实例变量(成员变量)
    

setter和getter方法

  1. setter和getter方法的使用场合

     @public的成员可以随意被赋植,应该使用setget方法来管理成员变量的访问
    
  2. setter方法

    作用:用来设置成员变量,可以在方法里面过滤一些不合理的值
    命名规范:方法以set开头,而且后面跟上成员变量名,成员变量名必须首字母大写,尽量形参名称不要与成员变量名重名(成员变量名最好以下划线 _ 开头)
    返回值:一般为void
    
  3. getter方法

    作用:返回对象内部的成员变量
    命名规范:方法名和成员变量名同名
    返回值:一般与成员变量的类型相同  
    

self关键字

  1. 成员变量和局部变量同名

     当成员变量和局部变量同名时,采取就近原则,访问的是局部变量
     当self访问成员变量,区分同名的局部变量
    
  2. 使用细节

     1. 出现的地方:所有的OC方法中(对象方法/类方法),不能出现在函数
     2. 作用:
         使用“self.属性”访问当前方法中的成员变量
         使用“self-> 成员变量”访问当前方法中public成员变量
         使用“[self 方法]”调用方法(类方法/实例方法)
     3. 类方法中self只能调用类方法,实例方法中self只能调用实例方法
    

继承

  1. 继承的概念

     1. is-a机制
     2. 即当创建的多个类有共同的属性和行为时,可以抽出一个类作为父类,在父类中定义相同的属性,声明实现相同的行为(方法);
     3. 子类可以使用父类的所有属性和方法,并且子类可以在父类的基础上拓补自己的属性和方法,包括重写父类方法。重写父类方法时,子类对象会优先调用子类重写后的方法。
     4. 子类属性和方法访问的过程: 如果子类没有相应的方法或属性,则去访问父类,一次递进知道找到NSObject根类,如果仍然没有找到相对应的方法和属性,则报错。
    
  2. 继承的专业术语

     父类/超类    superclass
     子类 subclasssubclasses
    
  3. 继承的细节

     单继承,不支持多继承
     子类和父类不能有相同的成员变量
     子类可以重写父类中声明的方法(在代码运行时,oc确保调用相应类的重写方的实现)
    
  4. 继承的优缺点

     优点:
     在不改变原来模型的基础上,拓充方法
     建立了类与类的联系
     抽取了公共代码
    
     缺点:
     耦合性强
    
  5. super关键字

     super既不是参数,也不是实例变量,而是oc编译器提供的功能
     用于提供一种在子类中显示调用父类的方法    
    
  6. 继承的局限性

     父类不能访问子类属性、调用子类方法
     不能继承累簇(如 NSString累簇)
    

多态

  1. 多态的基本概念

     某一类事物的多种形态
     OC对象具有多态性
    
  2. 多态的体现

     主要体现在继承下:向不同的对象发相同的消息,其呈现的行为不一样。(如DrawShape程序中,向不同图像的对象发送draw消息,其打印结果是不同的)。
     子类对象可以赋值给父类指针;
     如:Father *f = [children new];
     父类指针可以访问对应的属性和方法
     如: f.age = 23;  
         [f study];
    
  3. 多态的好处

     用父类接收参数,节省代码
    
  4. 多态的局限性

     不能访问子类的属性(可以考虑强制转换)
    
  5. 多态的细节

     动态绑定,在运行时根据对象的类型确定动态调用的方法
    

复合

复合包括组合和聚合

hasa机制
组合和聚合表示将各个部分组合在一起,用于表达整体与部分的关系。在面向对象的编程思想里,就是用已有类的对象封装新的类。
  • 组合 :表示一种强的、严格的整体与部分的关系,部分和整体的生命周期一样。 比如:人和人头
  • 聚合 :表示一种弱的整体与部分的关系,比如: 汽车和轮胎

Foundition框架

1. OC集合只能存储OC对象,不能存储c语言中的基本数据类型,如intfloatenumstruct,且不能在集合中存储nil

字符串

  1. 不可变字符串 : NSString *string1;
  2. 可变字符串 : NSMutableString *string2;

    对可变字符串的操作:

    2.1 增加元素

    string2 appendFormat:@"hello"];

    2.2 删除元素

    [string2 replaceCharacterInRange:NAMakeRange(2,3)];

    2.3 修改元素(替换)

    [string2 replaceCharacterInRange:NAMakeRange(2,3)withString:@"word"];

  3. 字符串的操作

    3.1 比较

    //判断两个字符串是否相等,返回的是BOOL值

    [str1 isEqualTo:str2];

    NSCompareResult res = [str1 copmare:str2];

    不区分大小写的比较:caseInsensitiveCompare

    有选择参数的比较: [str compare:str2 option:NSStringCompareOption]

    NSStringCompareOption选项可以传入的参数

     enum {
                NSCaseInsensitiveSearch = 1,   不区分大小写
                NSLiteralSearch = 2,           对于相等的字符串逐个比较
                NSBackwardsSearch = 4,         从后向前比较
               NSAnchoredSearch = 8,          限制比较从开始还是结尾
                NSNumericSearch = 64,          对于数字按数字比较
               NSDiacriticInsensitiveSearch = 128,     不区分音节
                NSWidthInsensitiveSearch = 256,         忽略full-width half-width (如 Unicode code point U+FF41 和 Unicode code point U+0061 的字母 “a”is equal)
                NSForcedOrderingSearch = 512,           对于不区分大小写比较相等的字符串,强制返回NSOderedAscending or NSOrderedDeascending (如“aa” is grater than “AA”)
                NSRegularExpressionSearch = 1024        treated as an ICU-compatible regular expression
         };
    

    NSCompareResult 有三种值:

     NSOrderedSame  两字符串相等
     NSOrderedAscending  str1 < str2
     NSOrderedDeascending  str1 > str2;
    

    3.2 求长度

    NSUInteger strlen = [str1 length];

    3.3 大小写转换

    str2 = [str1 uupercaseString];

    str2 = [str1 lowercaseString];

    3.4 获取文件前缀、后缀

    str2 =[str1 hasPrefix:@"word"];

    str2 = [str1 hasSuffix:@"txt"];

    3.5 获取子串

    //获取str2在str1中的位置,即range.location and range.length

    range = [str1 rangOfString:str3];

    range = [str1 rangOfString:@"hello"];

    //获取str1 第6个位置之后的字符串赋值给str2

    str2 = [str1 substringFromIndex:6];

    //获取str1 从开始到第6个位置之间的字符串赋值给str2

    str2 = [str1 substringTOIndex:6];

    //获取str1 从第6个位置开始长度为5的字符串赋值给str2

    str2 = [str1 substringWithRange:NSMakeRange(6,7)];

    3.6 文件路径的转换

    //间文件路径字符串str1 = @“~/test.html”的路径转换为绝对路径赋值给str2

    str2 = [str1 stringByExpandingTildeInPath];

    //间文件路径字符串str1 = @“/users/qingyun/test.html”的路径转换为相对路径赋值给str2

    str2 = [str1 stringByAbbreviatingWithTildeInPath];

    3.7 文件路径的扩展名

    str2 = [str1 pathExtension]; 此时 str2 = @“html”;

    3.7 删除文件路径的后缀

    str2 = [str1 stringByDeletePathExtension]; 此时 str2 = @“~/test”;

    3.9 追加字符串

    str1 = @”hello word”;

    str2 = [str1 stringByAppendingFormat:@"wellcom"]; 此时 str2 = @“hello word wellcom”;

数组

  1. 不可变数组 : NSArray *array1;
  2. 可变数组 : NSMutableArray *array2;

    数组初始化:

    NSArray *array1 = [NSArray arrayWithObjects:@"hello",@"word",@"two",nil];

    NSArray *array1 = @[@12,@34,@"hello",@"error"];

    //创建空数组

    NSMutableArray *array2 = [NSMutableArray array];

    //用已有的数组创建新数组

    NSMutableArray *array2 = [NSMutableArray arrayWithArray:array];

    //创建一个数组,并预分配内存

    NSMutableArray *array2 = [NSMutableArray arrayWithCapacity:40];

    对可变数组的操作:

    2.1 增加元素

    [array2 addObjects:@"hello"];

    2.2 删除元素

    //删除下标为2的对象

    [array2 removeObjectsAtIndex:2];

    //删除一定范围内的所有@“hello”

    [array2 removeObject:@"hello" inRange:NSMakeRange(2, 3)];

    [array3 removeObjectIdenticalTo:@"is" inRange:NSMakeRange(1, 5)];

    //删除该数组内的所有@“hello”

    [array2 removeObjectIdenticalTo:@"hello"];

    2.3 修改元素(替换)

    [array2 removeObjectsAtIndex:2 withObject:@"dog"];

    [array2 removeObjectsAtIndex:2 withObject:str];

    [array2 removeObjectsInRange:NSMakeRang(0,2) withObjectFromArray:array];

    2.4 插入元素

    [array2 insertObjects:str1 AtIndex:2];

    2.5 访问数组某个对象

    array2[下标]

字典

  1. 不可变数组 : NSDictionary *dictionary1;
  2. 可变数组 : NSMutableDictionary *dictionary2;

    字典初始化:

    Dictionary *dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:str1,@"hello",str2,@"word",str3,@"two",nil];

    Dictionary *dictionary1 = @{@"num1":@12,@"num2":@34,@"str1":@"hello",@"str2":@"error"};

    //创建空字典

    NSMutableDictionary *dictionary2 = [NSMutableDictionary dictionary];

    //用已有的字典创建新字典

    NSMutableDictionary *dictionary2 = [NSMutableDictionary dictionaryWithDictionary:array];

    //创建一个字典,并预分配内存

    NSMutableDictionary *dictionary2 = [NSMutableDictionary dictionaryWithCapacity:40];

    对可变字典的操作:

    2.1 增加元素

    [dictionary2 addObjects:(id)forKey:@"key"];

    2.2 删除元素

    [dictionary2 removeObjectForKey:@"key"];

    2.3 修改元素(替换)

    [dictionary2 setObject:(id)forKey:@"key"];

    2.4 访问字典

    dictionary2[@“key”];

    [dictionary2 objectForKey:@"key"]

装箱-开箱

  1. 对基本数据类型的装箱-NSNumber

    //装箱方法1

    NSNumber *number = [NSNumber numberWithChar:'X'];

    NSNumber *number = [NSNumber numberWithINT:23];

    NSNumber *number = [NSNumber numberWithBOOL:YES];

    NSNumber *number = [NSNumber numberWithDouble:34.5];

    //装箱方法2

    @23,@34.5

    //开箱

    [number charValue];

    [number intValue];

    [number BOOLValue];

    [number DoubleValue];

  2. 对所有非对象类型的装箱(包括基本数据类型)- NSValue

    //对NSRect,NSPoint,NSRange装箱,也可以对基本数据类型进行装箱

    NSRect rect = NSMakeRect(10,20,30,40);

    NSValue *value = [NSvalue valueWithBytes:&rect objCType:@encode(NSRect)];

    int a = 5;

    NSValue *value = [NSvalue valueWithBytes:&a objCType:@encode(int)];

    //开箱

    NSRect rect2 = {0};

    [value getValue:&rect];

    int b = 0;

    [value getValue:&b];

    //仅对NSRect,NSPoint,NSRange装箱

    NSValue *value = [NSValue valueWithRect];

    NSValue *value = [NSValue valueWithRange];

    NSValue *value = [NSValue valueWithPoint];

    //开箱

    NSRect rect2 = {0};

    [value rectValue];

    NSRange range = {0};

    [value rangeValue];

    NSPoint point = {0};

    [value pointValue];

枚举

//normal enumerator

NSEnumerator *enumer = [array objectEnumerator];

id obj;
while (obj = [enumer nextObject]) {
    NSLog(@"%@",obj);
}

NSEnumerator *enumer2 = [array reverseObjectEnumerator];
while (obj = [enumer2 nextObject]) {
    NSLog(@"%@",obj);
}

//fast enumerator

for (id obj2 in array) {
    NSLog(@"%@",obj2);
}

类别

  1. 类别的简述

    • 为现有的类(自定义的类、第三方的类或者是系统定义的类)添加一些新的行为;
    • 类别可以解决继承不能为累簇添加新方法的问题。
  2. 类别的声明和实现

    格式: 类名 + 类别名

    如:为NSString 创建一个类别 NSString+NumberConvenience

    只要保证类别名称唯一,可以向一个类中添加任意数量的类别。

    声明:

    @interface NSString (NumberConvenience)

    - (NSNumber *)lengthAsNumber;

    @end

    实现:

    @implementation NSString (NumberConvenience)

    - (NSNumber *)lengthAsNumber
    {

    }

    @end

  3. 类别的优缺点

    缺点:

     * 只能添加方法,只可以访问原始类的实例变量,无法向类别中添加新的实例变量
     * 名称冲突。类别具有最高优先级,即当类别中定义与对应类中已有的方法同名的方法,对象调用该方法时,会优先调用类别中定义的方法。
     * 多个Category中如果实现了相同的方法,只有最后一个参与编译的才会有效   
    

    优点:

     * 将类的实现代码分散到多个不同文件或框架中。
     * 可以创建对类中私有方法的前向引用,
     * 向对象添加非正式协议。
    
  4. 使用类别实现类的扩展

    类的扩展等同于在类声明的源代码中声明一个无名的(即括号“ () ”里面为空)类别,并实现;

    • 类的扩展可以在源代码中使用
    • 可以添加实例变量作为类的私有变量和方法
    • 可以将只读权限改为读写权限
    • 创建数量不限
  5. 利用类别分散实现代码的优点

     . 在大型的项目中, 一个类的实现可能非常大,并且.m文件不能分离。但是使用类别可以将一个类的实现分散且有规律的组织在不同的文件中。还可以将一个类的实现分散到不同的框架中。 
     . 编程人员可以更加容易阅读代码并实现多人合作编码
     . 版本管理降低冲突
     . 维护人员更容易理解代码
    
  6. 非常正式协议

    非正式协议就是为NSObject类创建一个类别;

  7. 响应选择器

    • 使用@selector()编译指令来指定选择器,圆括号里是具体的方法名。如:
1
2
3
4
(有几个参数要有几个冒号“ : ”)
如:
@selector(setEngine:)
@selector(setTire:atIndex:)
 - 选择器的类型关键字:SEL
 - \- (BOOL)respondsToSelector:(SEL)@Selector; 使用此方法可以判断某一对象是否可以执行指定的方法。 
1
QYStudent *student = [[QYStudent alloc]init];
 如: 
1
[student respondToSelector:(SEL)@selector(study)]; //对对象student判断其是否有study这个方法,有的话返回值为YES,没有的话返回值为NO。

协议

  1. 基本用途

    • 可以用来声明一大堆方法(不能声明成员变量)
    • 只要某个类遵守了这个协议,就相当于拥有这个协议中的所有方法声明
    • 只要父类遵守了某个协议,就相当于子类也遵守了
  2. 格式
    @protocol 协议名

    方法声明列表

    @end

    某个类遵守某个协议

    @interface 类名 : 父类名<协议名>

    @end

  3. 关键字

    协议中有2个关键字可以控制方法是否要实现(默认是@required),在大多数情况下,用途在于程序员之间的交流

    • @required: 该关键字以下且@optional关键字以上的方法必须要实现(若不实现,编译器会发出警告
    • @optional: 该关键字以下且@required关键字以上的方法可以选择性的实现
  4. 协议遵守协议

    • 一个协议可以遵守其他多个协议,多个协议之间用逗号 , 隔开

      • 一个协议遵守了其他协议,就相当于拥有了其他协议中的方法声明

      @protocol 协议名称 <协议1, 协议2>

      @end

  5. 基协议

    • NSObject是一个基类,最根本最基本的类,任何其他类最终都要继承它
    • 其实还有一个协议,名字也叫NSObject,它是一个基协议,最根本最基本的协议
    • NSObject协议中声明很多最基本的方法,比如description、retain、release等
    • 建议每个新的协议都要遵守NSObject协议
  6. 定义变量时指定协议

    // NSObject类型的对象,并且要遵守NSCopying协议

    • NSObject *obj;

      // 任何OC对象,并且要遵守NSCoding协议

    • id obj2;

内存管理

内存管理机制:引用计数

  1. 引用计数的计算

    • alloc 、new 、copy(copy生成接收对象的一个副本) //使用这三个方法创建对象时,对象的引用计数器为1
      • - (id) retain; //给对象发送retain消息后,对象的引用计数器加1
      • - (void) release; //给对像发送release消息后,对象的引用计数器减1
      • - (void)dealloc; //当一个对象的引用计数器变为0而即将被销毁时,Objective-C自动向对 象发送一条dealloc消息,我们通常都会在自己的对象中重写dealloc方法
      • - (unsigned) retainCount;//获取当前对象的引用计数器的值
  2. 非ARC环境下内存的管理

    当某个对象被持有有,[对象名 retain];
    当某个对象不再被持有时,[对象名 release];

  3. ARC环境下内存的管理

    • 规则

      只要还有一个强指针变量指向对象,对象就会保持在内存中

    • 强引用,弱引用

      ➢ 默认所有实例变量和局部变量都是Strong指针

      ➢ 弱指针指向的对象被回收后,弱指针会自动变为nil指针,不会引发野指针错误。其修饰符号为__weak;

    • 注意点

      ➢    不能调用release、retain、autorelease、retainCount
      

      ➢ 可以重写dealloc,但是不能调用[super dealloc]

      ➢ @property : 想长期拥有某个对象,应该用strong,其他对象用weak

      ➢ 其他基本数据类型依然用assign

      ➢ 两端互相引用时,一端用strong、一端用weak

      1. 自动释放池
    • 自动释放池是一个存放实体的集合,这些实体可能是对象,这些对象能够被自动释放。
    • / - (id) autorelease; //是NSObject类提供的方法,此方法在某一个预定的时候,向对象发送release消息,返回值是接收消息的对象。实际上当给一个对象发送autorelease消息的时候,就是将这个对象添加到的自动释放池(NSAutoreleasePool)中,当自动释放池销毁时,会向该池中的所有对象发送release消息。

      如: - (NSString ) description
      {
      NSString
      desc;
      desc = [[NSString alloc] initWithFormat: @” I am %d years old”,29];
      return ([desc autorelease]);
      }

  4. 内存管理规则

    • 如果我使用了new , alloc 或者copy方法获得一个对象,则我必须释放或自释放该对象。
    • 如果你对对象调用了retain消息,那么你必须负责释放(release)这个对象,保证retain和release的使用次数相等。

拷贝

  1. 浅拷贝(shallow copy)

    不会复制所引用的对象,新复制的对象只会指向现有的引用对象上。(引用计数加 1 ,地址不变)

  2. 深拷贝(deep copy)

    真正意义的复制概念。得到的结果是多个,而非只是对象的引用。(引用计数 不变 ,地址发生变化)

  3. 关键字

    copy:对不可变的集合copy为浅拷贝,对可变的集合copy为深拷贝

    mutableCopy:对可变的或不可变的集合mutableCopy都是深拷贝,但是对于集合内部对象的拷贝时浅拷贝。

BLOCK

  1. 基本概念

    代码块本质上是和其他变量类似。不同的是,代码块存储的数据是一个函数体。使用代码块时,可以像调用其他标准函数一样,传入参数数,并得到返回值。

* Block封装了一段代码,可以在任何时候执行
* Block可以作为函数参数或者函数的返回值,而其本身又可以带输入参数或返回值。
* 苹果官方建议尽量多用block。在多线程、异步任务、集合遍历、集合排序、动画转场用的很多
  1. 定义

     int (^MySum)(int, int) = ^(int a, int b) {
     return a+b;
     };
    

    定义了一个叫MySum的blocks对象,它带有两个int参数,返回int。等式右边就是blocks的具体实现

  2. 对变量的访问权限

    • 对全局变量具有读写权限
    • 对静态变量具有读写权限
    • 对局部变量只有访问权限(可以用__block修饰局部变量,这样可以对其进行修改)
  3. 与函数指针的对比

    定义函数指针
    int (p)(int,int);
    *定义Blocks

    int (^Blocks)(int,int);

    调用函数指针
    (p)(10, 20);
    *调用Blocks

    Blocks(10, 20);

  4. typedef和赋值

    • 在声明的同时定义变量,然后赋值
      int (^MySum)(int,int) = ^(int a,int b) {
      return a + b;
      };

    • 也可先用typedef先声明类型,再定义变量进行赋值
      typedef int (^MySum)(int,int);
      MySum sum = ^(int a,int b) {
      return a + b;
      };

KVC(Key Valuble Coding)

  1. 基本概念
    • 是一种间接更改对象状态(或者说是属性值)的方式:key-value coding 简称KVC.
    • 主要本质特点是采用字符串来标识对象的属性变量,并可以利用这个标识来更改对象的状态(或者说是属性值)
  2. 基本用法

    • / - (id)valueForKey:(NSString *)key //以key作为标识符,获取其对应的属性值
    • / - (void)setValue:(id)value forKey:(NSString *)key //以key作为标识符设置其对应的属性值。
  3. 调用机制

    • valueForKey:会首先查找以参数名命名(格式为-key或者isKey)的getter方法,如果找到的话则调用这个方法;如果没有找到这样的getter方法,它将会在对象内部寻找名称格式为_key或者key的实例变量,然后返回。
    • setValue:forKey:的机制跟valueForKey相似。它首先查找参数名命名的setter方法,如果找到的话则完成设置;如果没有找到setter方法, 则直接在类中找到名称格式为_key或者key的实例变量, 然后将value赋值给它。
  4. 键路径

    键路径的概念和表示:可以在对象和不同的变量名称之间用圆点分开来表示。

    • -(id)valueForKeyPath:(NSString *)keyPath //以keyPath作为标识符,获取其对应的属性值
    • -(void)setValue:(id)value forKeyPath:(NSString *)keyPath //以keyPath为标识符,设置其对应的属性的值。

通配符 《系统级别》

  1. {}

    touch {1,2,3,4,6,a,c,b,hello,t}.c

    // 同时创建 1.c,2.c,3.c,4.c,6.c,a.c,c.c,b.c,hello.c,t.c文件

  2. *

    ls *.c

    //列出所有以 .c为后缀的文件

  3. ?

    ls ??h*.c

    //列出第三个字符为“h”,且以.c为后缀的所有文件

  4. []

    ls [0-9].c

    //列出以数字0-9为文件名的.c文件

  5. !

    ls ![0-9].c

    //列出所有不是以数字0-9为文件名的.c文件

谓词

  1. 谓词的定义

    谓词使用了KVC机制。

    NSPredicate *predicate = [[NSPredicate prdicateWithFormat:@string]];

    //实历化一个谓词对象.

    NSArray predicateArr = [对象名 filteredArrayUsingPredicate predicate];

    //向对象发消息,过滤出满足谓词条件的内容,并存放到数组predicateArr中; (filteredArrayPredicate:NSPredicate 方法的返回值时NSArray 类型)

  2. 谓词中的操作符

    谓词操作符不区分大小写

    • 关系运算符

      { > < >= <= == != }

    • 逻辑运算符

      {&&(and) ||(or) !}

1
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name != 'lisi' and age > 12"];
* 范围运算符

    `{between in}`
1
2
3
4
predicate = [NSPredicate predicateWithFormat:@"age in {23,25}"];
//仅仅过滤出 age = 23 和 age = 25 的信息
predicate = [NSPredicate predicateWithFormat:@"age between {23,25}"];
//过滤出 23 >= age <= 25 的信息
* 通配符

    `{* ? 主要与like一起使用}`
1
2
predicate = [NSPredicate predicateWithFormat:@"name like '??a*'"];
//过滤name第三个字母为a的信息
* 字符串特有操作符

    `{contains like endswith beginswith [c]不区分大小写[d]不区分音节[cd]}`
1
2
predicate = [NSPredicate predicateWithFormat:@"name endswith[cd] 'u' and name contains[cd] 'ao'"];
//过滤name以‘u’结尾 且 包含 “ao”的信息
* 集合中的操作符

    `{ANY ALL}`
1
2
3
4
5
6
7
predicate = [NSPredicate predicateWithFormat:@"ALL age > 10"];
if ([predicate evaluateWithObject:Arr]) {
NSLog(@"evaluable");
}else {
NSLog(@"It's not evaluable ");
}
//判断数组Arr中的对象中age是否全部大于10
* 谓词模板

    `{$  %K}`
1
2
3
4
5
6
7
8
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age between $RANGE"];
NSArray *arr = @[@20,@50];
NSDictionary *dic = @{@"RANGE":arr};
//过滤 20 >= age <= 50的信息
NSString *keyPath = @"age";
predicate = [NSPredicate predicateWithFormat:@"%K > %@",keyPath,@20];
//过滤age > 20 的信息

正则表达式 《工具级别》

选择

| 竖直分隔符代表选择。例如,“grey | gray”可以匹配grey或gray

数量限定

  • +号代前面的字符至少要出现一次,可以出现多次。例如,“goo + gle”可以匹配google,gooogle,goooogle等
  • ?号代表前面的字符最多只能出现一次,可以不出现。例如,“colour?r”可以匹配color或者colour
  • 星号代表前面的字符可以不出现,可以出现一次或多次。例如,”0\42”匹配42,042,0042,0004等。
  • “{n}”代表前面的字符要出现n次,“{2,6}”代表前面的字符可以选择性的出现2-6次,例如,”go{2}gle”可以匹配google

匹配
“()”圆括号可以用来定义操作符的范围和优先度。例如,“gr(a|e)y”等价与“gray|grey”,”(grand)?father” 可以匹配father和grandfather。

^ $符号

  • ^符号代表开始,例如,“^b”可以匹配以字符b开始的一类字符串
  • $符号代表结束,例如,“x$”可以匹配以字符x结束的一类字符串,“^$”代表空

.符号
.点符号,代表可以是任意字符。例如,“^a.{3}[0-9]+eh(hello)$”可以匹配ad_dehhello,a23d4ehhello,asdf345ehhello等

1
以上规则可以综合使用

正则表达式可以用在grep,awk,sed,gas,find,等命令中,

  • grep | ‘[a-z]{5}zsh$’ dotfiles 过滤dotifiles目录下的所有文件及目录
  • ls | grep ‘^d’ ls命令列出当前目录下的以d开头的文件包括目录
  • grep | -R ‘hello’ ./* 递归的查看根路径下的所有包含hello字符串的内容(-RE 递归的查找,支持正则表达式)
  • find . -name ‘hello’查看名字为hello的文件的路径,
  • find . -type d 查看当前目录下的所有文件夹的路径
  • sed -RE ‘/^_.*(false)$/‘ /etc/passwd 查看passwd文件内容不是以下划线开始且以false结束的内容

image