目錄
1. 語法特性
2. 控制語句
3. 數(shù)據(jù)結構
4. 數(shù)據(jù)類型
1.語法特性
OC:面向?qū)ο?
封裝
將所有事物都封裝為類(方便復用,安全)
繼承
子類繼承父類的所有屬性和方法(減少冗余)
多態(tài)
動態(tài)運行時語言(方便復用)簡單的說措伐,就是一句話:允許將子類類型的指針賦值給父類類型的指針崔赌。
動態(tài)類型(只有在運行時才能確定對象的類型肺素,如id修飾的對象/父類指針傳入子類對象。RunTime機制可以動態(tài)替換或添加方法)
動態(tài)綁定(對象的類型確定后匕荸,其所對應的屬性和方法就確定了)
動態(tài)加載(在運行時根據(jù)需要加載所需資源:如@2x@3x圖片)
2. 控制語句
同Java同C 都是以C為基礎
2.1. 判斷語句
if判斷
判斷條件---非0則真(1) 為真則真(@"sb"!= nil) 非假則真( !0 )
if(i==1){
}else if(i==2){
}else{
}
switch判斷
當條件多于3個時使用switch
switch(x){ // 只能是整型汁雷、char
case 1:{
// 多個語句時必須加{}介时,否則報錯
break;
}
default:
}
2.2 循環(huán)語句
for循環(huán)
for(int i=0;i<10;i++){ // 1可省(寫在上面) 3可仕饴瘛(寫在里面)
}
for(id item in array){
}
for(id key in dict.allKeys){
dict[key]
}
for(id value in dict.allValues){
}
where循環(huán)
while(i<10){
}
do{
}while(i<10);
break; 跳出循環(huán)
continue; 跳出本次循環(huán)淫痰,開始下次循環(huán)
3. 數(shù)據(jù)結構
數(shù)據(jù)結構:計算機組織存儲數(shù)據(jù)的方式。
數(shù)據(jù)之間的相互關系稱為結構整份,分為邏輯結構和物理結構待错。
邏輯結構:
集合結構(所有數(shù)據(jù)的數(shù)據(jù)類型相同)、
線性結構(一對一)烈评、
樹性結構(一對多)火俄、
圖像結構(多對多)
物理結構:
棧(由編譯器自動管理)、
堆(需要手動創(chuàng)建并管理讲冠,容易造成內(nèi)存泄漏)瓜客、
隊列、
鏈表(數(shù)據(jù)在內(nèi)存中是不連續(xù)的,通過節(jié)點中的指針聯(lián)系在一塊)忆家、
數(shù)組(數(shù)據(jù)在內(nèi)存中是連續(xù)的犹菇,每個元素所占內(nèi)存相同,可通過下標迅速訪問)
內(nèi)存的分區(qū)情況:
代碼區(qū)(存放程序代碼)
數(shù)據(jù)區(qū)(存放常量芽卿、全局變量揭芍、靜態(tài)變量)
堆區(qū)(由程序員手動申請并釋放)
棧區(qū)(由編譯器管理,局部變量卸例、函數(shù)參數(shù))
4.數(shù)據(jù)類型
分為
基本數(shù)據(jù)類型
枚舉称杨、結構體、類類型
4.1.基本數(shù)據(jù)類型
int(默認值為0)
float
double
char
BOOL(默認:false,非0則真 , !真則假)
NSInteger
4.2.枚舉
方式一
將有限個相關值合在一起
typedef enum{ // 定義+取別名
TypeA=0,
TypeB,
}Type;
Type type=TypeA;
enum Type{ // 定義
TypeA=0,
TypeB,
};
enum Type type=TypeA;
方式二
推薦使用---混編時不報錯
typedef NS_ENUM(NSInteger,TYPE){
TYPE_ADD,
TYPE_SUB,
};
typedef NS_OPTIONS(NSInteger, TYPE){
TYPE_ADD = 1 << 0, // 2的0次方
TYPE_SUB = 1 << 1, // 2的1次方
};
@property (nonatomic,assign) TYPE type;
有 << 則可以使用 | (如:TYPE_ADD|TYPE_SUB)
int type=TYPE_ADD|TYPE_SUB type&TYPE_ADD為TYPE_ADD的值則有TYPE_ADD
原理:
int value = TYPE_ADD | TYPE_SUB;
轉成二進制:
TYPE_ADD: 0 0 0 1
|
TYPE_SUB: 0 0 1 0
----------------
value: 0 0 1 1
上面是使用 | 得出value的值為0011 (|的意思是有一個為1結果就為1)
下面是使用 & 判斷輸出的值(&的意思就是有二個為1結果才為1)
value: 0 0 1 1 value: 0 0 1 1
& &
nameA: 0 0 0 1 nameB: 0 0 1 0
---------------- ----------------
結果值: 0 0 0 1 結果值: 0 0 1 0
4.3. 結構體
不能封裝行為
struct Person{ // 定義
char *name;
int age;
};
typedef struct Person MyPerson; // 取別名
typedef struct{ // 定義+取別名
char *name;
int age;
}MyPerson;
//
MyPerson person={"xiaoming",15};
struct Person person={"xiaoming",15};
//
person.name="xiaozhang";
person.age=21;
//
struct Person *person1=&person;
person1->name="xiaozhang"; // 不能使用 .
person1->age=21;
4.4 類類型
系統(tǒng)類類型
非集合類
NSNumer(基礎數(shù)據(jù)類型互轉對象類型)(例:@15, [num integerValue])
NSString筷转、NSMutableString
NSDate
集合類
NSArray姑原、NSMutableArray (只能存儲對象類型)
NSDictionary、NSMutableDictionary (只能存儲對象類型)
NSSet
自定義類類型
自定義類名 繼承:NSObject
NSObject-所有對象類型的基類
id可以是任意類類型(OC動態(tài)運行時語言:只有在運行時才能確定變量的類型)(id a=dog 沒有*呜舒,id自帶*)
父類 *f=子實例; [f 子獨有方法]; 編譯時不會報錯锭汛,運行時崩
- 系統(tǒng)類類型
NSString
創(chuàng)建方式
NSString *contentStr=@"";
NSString *contentStr=[NSString stringWithString:@""];
NSString *contentStr=[NSString stringWithFormat:@"%@",@""];
NSString *contentStr=[[NSString alloc]initWithFormat:@"%@",@""];
改
// 追加字符串(生成的是新的字符串)
NSString *newStr=[contentStr stringByAppendingString:@""];
NSString *newStr=[contentStr stringByAppendingFormat:@"%@",@""];
// 截取字符串
[contentStr substringFromIndex:0];
[contentStr substringWithRange:NSMakeRange(0, 10)];
[contentStr substringToIndex:10];
// 字符串->array
NSArray *arr=[contentStr componentsSeparatedByString:@","];
// 轉大小寫
NSString *upStr=[contentStr uppercaseString];
NSString *lowStr=[contentStr lowercaseString];
查
// 字符串的長度
NSUInteger length=contentStr.length;
// 字符串某位置的字符
unichar xChar=[contentStr characterAtIndex:0];
// 字符串是否相同
[contentStr isEqualToString:@"ddd"]
// 某字符串的range
NSRange range=[contentStr rangeOfString:@"xx"];
// 是否不包含字符串xx
[contentStr rangeOfString:@"xx"].location == NSNotFound
// 是否包含某字符串xx
BOOL isHave=[contentStr containsString:@"xx"];
// 是否有 前綴xx/后綴xx
[contentStr hasPrefix:@"xx"];
[contentStr hasSuffix:@"xx"];
// 共同的前綴
[contentStr commonPrefixWithString:@"xx123" options:NSLiteralSearch];
NSMutableString : NSString
// 創(chuàng)建
NSMutableString *muStr=[NSMutableString stringWithString:@""];
NSMutableString *muStr=[NSMutableString stringWithFormat:@"%@",@""];
NSMutableString *muStr=[NSMutableString stringWithCapacity:10];
改
// 插入
[muStr insertString:@"" atIndex:0];
// 刪除
[muStr deleteCharactersInRange:NSMakeRange(0, 10)];
// 追加
[muStr appendString:@""];
[muStr appendFormat:@"%@",@""];
NSArray
// 創(chuàng)建
NSArray *arr1 = [[NSArray alloc] initWithObjects:@"a", @"b", @"c", nil];
NSArray *arr11= [[NSArray alloc] initWithArray:arr1];
NSArray *arr12= [[NSArray alloc] arrayWithArray:arr1];
NSArray *arr2 = [NSArray arrayWithObjects:@"a", @"b", @"c", nil]; // 類方法
NSArray *arr3 = @[@"a", @"b", @“c”,@1,@YES]; // 元素不可nil,否則崩
改
// 追加(生成新數(shù)組)
NSArray *newArr=[arr arrayByAddingObjectsFromArray:@[]];
NSArray *newArr=[arr arrayByAddingObject:@""];
// array->str
NSString *str=[arr componentsJoinedByString:@","];
查
arr.count
[arr count]
arr[0]
[arr firstObject]
[arr lastObject]
// 是否包含某元素
BOOL isHave=[arr containsObject:@""];
NSMutableArray
創(chuàng)建
NSMutableArray *mutArr = [@[@"a", @"b", @"c"] mutableCopy]; // 轉mutable
NSMutableArray *mutArr = [[NSMutableArrary alloc]initWithCapacity:10]; // 預存放大小
NSMutableArray *mutArr = [[NSMutableArray alloc]init];
NSMutableArray *mutArr = [NSMutableArray array];
NSMutableArray *mutArr = [[NSMutableArray alloc]initWithObjects:@“”,@“”,nil];
NSMutableArray *mutArr = [NSMutableArray arrayWithObjects:@“”,@“”,nil];
NSMutableArray *mutArr = [[NSMutableArray alloc]initWithArray:arr1];
NSMutableArray *mutArr = [NSMutableArray arrayWithArray:arr1];
改
// 增
[mutArr addObject:@“12”];
[mutArr addObjectsFromArray:@[@"",@""]];
[mutArr insertObjectAtIndex:0];
[mutArr insertObjects:@[@"",@""] atIndexes:[NSIndexSet indexSetWithIndex:0]];
// 刪
[mutArr removeObject:@“12”];
[mutArr removeObjectAtIndex:0];
[mutArr removeObjectsAtIndexes:[NSIndexSet indexSetWithIndex:0]];
[mutArr removeObjectsInRange:NSMakeRange(1,1)]; // 從1刪長度1
[mutArr removeObject:@"xx" inRange:NSMakeRange(0, 10)];
[mutArr removeObjectsInArray:@[@"",@""]];
[mutArr removeLastObject];
[mutArr removeFirstObject];
[mutArr removeAllObjects];
// 換
[mutArr exchangeObjectAtIndex:0 withObjectAtIndex:1];
[mutArr replaceObjectAtIndex:0 withObject:@""];
[mutArr replaceObjectsAtIndexes:[NSIndexSet indexSetWithIndex:0] withObjects:@[@"",@""]];
[mutArr replaceObjectsInRange:NSMakeRange(0, 10) withObjectsFromArray:@[@"",@""]];
[mutArr replaceObjectsInRange:NSMakeRange(0, 10) withObjectsFromArray:@[@"",@""] range:NSMakeRange(0, 1)];
查
id item=[mutArr objectAtIndex:0];
NSInteger index=[mutArr indexOfObject:item];
id item=[mutArr firstObject];
id lastItem=[mutArr lastObject];
BOOL isHave=[mutArr contatinsObject:@“”];
for (int i=0;i<[mutArr count];i++){ // for循環(huán)
}
NSDictionary
// 創(chuàng)建
NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"vA", @"kA",@"vB", @"kB",nil];
NSDictionary *dict2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"vA", @"kA",@"vB", @"kB",nil];
NSDictionary *dict3 = @{@"kA":@"vA",@"kB":@"vB"}; // 元素不可nil袭蝗,否則崩
NSDictionary *dict4 = [[NSDictionary alloc] initWithDictionary:dict1];
data<->dict
// data->dict
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
// dict->data
NSData *data=[NSJSONSerialization dataWithJSONObject:dict NSJSONWritingPrettyPrinted error:nil];
查
id object=dict1[@"key"];
id object=[dict1 objectForKey:@"key"];
NSArray *allKeys=[dict1 allKeys];
NSArray *allValues=[dict1 allValues];
NSMutableDictionary
創(chuàng)建
NSMutableDictionary *dict5 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dict6 = [[NSMutableDictionary alloc] initWithDictionary:dict1];
NSMutableDictionary *dict7 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"vA", @"kA",@"vB", @"kB",nil];
改
[dict4 setObject:@"" forKey:@""];
[dict4 removeObjectForKey:@""];
NSSet(幾乎不用)
NSSet *set=[[NSSet alloc]initWithObjects:@“”,@“”,nil];
NSSet *set=[[NSSet setWithObjects:@“”,@“”,nil];
NSCharacterSet(用于分割字符串唤殴、中文編碼)
// 分割字符串
NSCharacterSet *cSet=[NSCharacterSet characterSetWithCharactersInString:@“#$%”];
NSString *str=@“ddddd#fff%fff$dd”;
NSArray *arr=[str componentsSeperatedByCharactersInSet:cSet];
// url中文編碼
NSCharacterSet *set2=[NSCharacterSet URLFragmentAllowedCharacterSet];
[str stringByAddingPercentEncodingWithAllowedCharacters:set2];
NSDate
// 根據(jù)時間戳(毫秒 /1000=秒)
NSDate *date=[[NSDate alloc]initWithTimeIntervalSince1970:time/1000];
// 格式類
NSDateFormatter *format=[NSDateFormatter new];
// 格式
[format setDateFormat:@"yyyy/MM/dd HH:mm:ss"]; // 自定義 HH為24小時制,hh為12小時制
// date轉str
NSString *timeS=[format stringFromDate:date];
// str轉date
NSDate *date = [format dateFromString:@"2010/09/09 13:14:56"];
// 獲取當前時間
NSDate *date = [NSDate date];
// 當前時間5s后
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:5];
// 從1970-1-1 00:00:00 開始1000s
NSDate *date=[[NSDate alloc]initWithTimeIntervalSince1970:1000];
// 從1970-1-1 00:00:00 的秒數(shù)
NSTimeInterval interval = [date timeIntervalSince1970];
// 返回舊 新
NSDate *firstDate=[date1 earlierDate:date2];
NSDate *lastDate=[date1 laterDate:date2];
// 2個date的時間差
NSTimeInterval interval=[date1 timeIntervalSinceDate date2];
// date1加秒數(shù) 得到date2
NSDate *date2 = [date1 dateByAddingTimeInterval:60];
根據(jù)字符串 返回星期幾
/**
參數(shù):時間字符串到腥,格式
返回:@"星期幾"
*/
+(NSString *)getWeekdayWithDateStr:(NSString *)dateStr withFormatStr:(NSString *)formatStr{
//
NSArray *weekdayArr=@[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
// 日歷(NSCalendarIdentifierGregorian)
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
// date
NSDateFormatter *dateFormat=[NSDateFormatter new];
[dateFormat setDateFormat:formatStr];
NSDate *date=[dateFormat dateFromString:dateStr];
// comps
NSDateComponents *comps=[calendar components:NSCalendarUnitWeekday fromDate:date];
return weekdayArr[[comps weekday]];
}
- 自定義類
使用Dog類
// 新建一個對象
Dog *dog=[[Dog alloc] init];
// 使用該對象的屬性/方法
dog.dogName // 位于=左側則是設置值(調(diào)用set方法) 朵逝, 位于=右側則是獲取值(調(diào)用get方法)
[dog run];
自定義Dog類
// 接口.h文件(用于外部調(diào)用)
@interface Dog:NSObject{
NSString *_dogName; // 屬性用{}與方法分開,不能在setDogName:方法中用self.(本質(zhì)是調(diào)用setDogName:)造成循環(huán)調(diào)用乡范,可以在其他方法中用self. , 但為了統(tǒng)一格式:統(tǒng)一用 _變量名(聲明是 調(diào)用亦是)
}
-(void)run; // 實例方法
-(void)run:(int)count; // 實例方法(帶參)
-(void)run:(int)count withLength:(int)length; // 實例方法(帶多參)
+(int)Legs; // 類方法
@end
// 實現(xiàn).m文件(具體實現(xiàn))
@implementation Dog
static NSString *const kM = @"sb"; // static修飾全局變量時表示:只在本類內(nèi)部使用 const修飾常量(const修飾“右邊” const *kM 則表示指向不可變 內(nèi)容可變 * const kM 則表示kM及內(nèi)容不可變 *kM即指向可變)
-(void)run{}
-(void)run:(int)count{}
-(void)run:(int)count withLength:(int)length{}
+(int)Legs{
return 4;
}
@end
5. 關鍵字
nullable nonnull
只可以修飾類類型
nullable :可以為nil(默認)
nonnull :不可以為nil
屬性
@property (nonatomic,strong,nonnull) NSArray *muArr;
@property (nonatomic,strong) NSArray * __nonnull muArra;
@property (nonatomic,strong) NSArray * _Nonnull muArray;
方法
-(void)func:(nonnull NSString *)str{}
-(void)funct:(NSString * _Nonnull)str{}
-(void)functi:(NSString *__nonnull)str{}
對于屬性的作用:有個提示
對于方法的作用:有個警告提示
NS_ASSUME_NONNULL_BEGIN
NS_ASSUME_NONNULL_END
null_resettable
_Null_unspecified
__kindof
6. 泛型
@property (nonatomic,strong) NSMutableArray<NSString *> *muArr;
從數(shù)組中取出的元素可以直接使用其屬性或方法
添錯類型有警告提示配名,添加時有提示
7. 協(xié)議delegate
1.協(xié)議
@protocol MyDelegate<NSObject>
@required
@optional
-(void)run;
@end
2. A類 dele屬性
@property(nonatomic,weak) id<MyDelegate> delegate;
需要的地方 判斷dele是否有方法后執(zhí)行[self.dele 方法];
3. B類 遵守協(xié)議
B類名<協(xié)議>
實現(xiàn)協(xié)議方法
110. 其他小知識
@class 類名 // 聲明有此類
.h中用@class聲明要用到的其他類,.m中再#import "" (可減少編譯時間)
self.屬性: 會首先調(diào)用set/get方法 (兼容懶加載晋辆,統(tǒng)一格式)
_屬性:會直接訪問屬性值
== 比較指針
instancetype:代表本類型(僅用于本類)
-(instancetype)init(){
self=[super init]
if(self){
}
return self
}
C:
[函數(shù)] 調(diào)用在實現(xiàn)之前渠脉,要進行聲明
聲明: 返回類型 函數(shù)名(參數(shù)類型 參數(shù)名);
實現(xiàn): 返回類型 函數(shù)名(參數(shù)類型 參數(shù)名){}
調(diào)用: int x=函數(shù)名(參值)栈拖;
所有數(shù)據(jù)類型要用()括起來
類型轉換(強轉)
(UIImageView*)view (NSNumber*)@"123"
浮點型+整型==浮點型(可直接操作连舍,精度為最大的那個,當函數(shù)要求返回類型為低精度時直接轉)
不支持函數(shù)重載(JAVA C++支持)
- typedef
typedef重定義數(shù)據(jù)類型---給類型取別名
// 用MyInt代替int(安全)
typedef int MyInt;
// 枚舉(Type typeA)
typedef enum{
TypeA=0,
TypeB,
}Type;
// struct (MyPerson person)
typedef struct Person{
char *name;
int age;
}MyPerson;
// block (MyBlock myBlock)
typedef void (^MyBlock)(NSString *content);
// C函數(shù)
typede void (*MyMehod)(char *content)
// C數(shù)組
typedef int (*Arr)[10];
為復雜聲明取別名
1.
舉例:void (*xxx[10]) (void (*)());
解:typedef void (*VoidFun)();
typedef void (*Fun)(VoidFun);
答:Fun xxx[10];
2.
舉例:doube(*)() (*xxx)[9];
解:typedef doube(*VoidFun)();
typedef VoidFun (*Point)[9];
答:Point xxx;
小記:[] 優(yōu)先級高于*
注意:
1.
const int *a=10;
a++;
正確
typedef int* YTInt;
const YTInt a=3;
a++;
報錯
原因:將YTInt整體作為數(shù)據(jù)類型,const直接修飾了a涩哟,導致a不可變索赏,*a可變。
- "重載"
JAVA(C++同理)
public interface Person{
}
public class Student implements Person{
}
public class Adult implements Person{
}
public class Run{
public void read(Person person){
System.out.println("person read");
}
public void read(Student person){
System.out.println("Student read");
}
public void read(Adult person){
System.out.println("Adult read");
}
}
Person person=new Student();
Read readM=newRead();
readM.read(person);
會輸出person read贴彼,不是想要的結果潜腻。直接作為參數(shù)放進去,不會識別器仗,調(diào)用方法可識別(因此給person加一個方法---readM作為參數(shù)傳入融涣,在添加的方法中調(diào)用read方法)童番,這樣一來就先識別了類。
解決:
添加方法
public interface Person{
public void goRead(Read read);
}
public class Student implements Person{
public void read(Read read){
read.read(this);
}
}
public class Adult implements Person{
public void read(Read read){
read.read(this);
}
}
Person person=new Studnt();
Read read=newRead();
person.goRead(read);
OC不支持重載
// 利用SEL可實現(xiàn)“重載”
SEL selector = NSSelectorFromString(@"");
if ([self respondsToSelector:selector]) {
[self performSelector:selector withObject:@"參數(shù)對象"];
}
- main.m 程序主入口
// 包含系統(tǒng)基礎庫
#import <Foundation/Foundation.h>
// 主函數(shù)(程序入口)
int main(int argc, const char * argv[]) {
// 自動釋放池(內(nèi)存管理方式之一)
@autoreleasepool {
// 打印
NSLog(@"Hello, World!"); // ; 語句分隔符(所有語句)
NSLog(@"%@",@"字符串");
}
return 0;
}
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
// 創(chuàng)建一個UIApplication對象,和AppDelegate對象(遵守<UIApplicationDelegate> )
// 第3個參數(shù)等價于:[UIApplication class](也可以是其子類) 第4個參數(shù):遵守<UIApplicationDelegate> 的一個類
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}