類:NSObject 、NSString、NSMutableString、NSNumber、NSValue、NSDate、NSDateFormatter、NSRange、Collections:NSSet、NSArray(Ordered、Copy)、NSMutableArray、NSMutableSet、NSDictionaryios
========================================================================================數組
知識點app
1、NSObject類函數
1.NSObject的概述學習
提供了系統運行時的一些基本功能編碼
1.對象的建立、銷燬atom
alloc init new deallocspa
2. 類的初始化翻譯
1.類加載的時候,自動調用+load方法 指針
2.第一次使用類的時候,自動調用+initailize方法
類在使用以前會執行此方法,而且只執行一次(直接能夠在.m中調用此方法)
2.copy方法
1.並非全部對象都有copy方法
2.若是一個對象支持copy功能,會將對象複製一份(深拷貝)
a.首先要遵照協議NSCopying協議.h文件,
b.必須實現copyWithZone方法協議.m文件
3.若是不但想複製對象,並且還要複製對象的值,
通常還要重寫屬性的有參的初始化方法,把self.參數值一塊兒經過return返回
TRStudent.h
#import <Foundation/Foundation.h>
@interface TRStudent : NSObject<NSCopying>//遵照NSCopying協議,才能實現深拷貝
@property int i;
-(id)initWithI:(int)i;
@end
TRStudent.m
#import "TRStudent.h"
@implementation TRStudent
+(void)load{
NSLog(@"load");
}
+(void)initialize{
NSLog(@"initialize");
}
//初始化方法
-(id)initWithI:(int)i{
if ([super init]) {
self.i=i;
}
return self;
}
//遵照NSCopying協議,實現方法
-(id)copyWithZone:(NSZone *)zone{
return [[TRStudent alloc]initWithI:self.i];//深拷貝屬性
}
@end
main.m
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRStudent* p=[[TRStudent alloc]init];
p.i=10;
TRStudent *p2=p;//淺拷貝 指向的地址同樣
TRStudent *p3=[p copy];//深拷貝,指向的地址不同
NSLog(@"p:%p",p);
NSLog(@"p2:%p",p2);
NSLog(@"p3:%p %d",p3,p3.i);//深拷貝屬性
}
return 0;
}
結果:
load
initialize
p:0x100601a80
p2:0x100601a80
p3:0x100600650 10
4.copy還能夠用在聲明式屬性中,可是注意程序的本質發生改變,會自動向實例變量發送copy消息,實例變量必須遵照協議/實現
TRBook.h
#import <Foundation/Foundation.h>
@interface TRBook : NSObject<NSCopying>
@property(nonatomic,assign)int price;
@end
TRBook.m
#import "TRBook.h"
@implementation TRBook
-(id)initWithPrice:(int)price{
self = [super init];
if (self) {
self.price = price;
}
return self;
}
- (id)copyWithZone:(NSZone *)zone{
return [[TRBook alloc]initWithPrice:self.price];
}
@end
TRStudent.h
#import <Foundation/Foundation.h>
#import "TRBook.h"
@interface TRStudent : NSObject
//@property(retain)TRBook *book;
@property(copy)TRBook *book;
-(void)study;
@end
TRStudent.m
#import "TRStudent.h"
@implementation TRStudent
-(void)study{
NSLog(@"學生看書 price:%d add:%p",self.book.price,self.book);
}
@end
main.m
TRBook *sanguo = [[TRBook alloc]init];
sanguo.price = 10;
NSLog(@"sanguo:%p",sanguo);
TRStudent *stu = [[TRStudent alloc]init];
stu.book = sanguo;
[stu study];
結果:
sanguo:0x100203af0
學生看書 price:10 add:0x1004006a0
2、類對象
1.類的對象:關注的是類的代碼信息,須要比較類的數據的時候須要使用類的對象。
2.類對象:關注的是對象的數據信息,須要比較類的代碼的時候須要使用類對象。
3.比較類信息
1、向類發送class消息,能夠建立類對象。
Class class = [TRStudent class];
2、判斷
1.判斷一個引用指向的對象是不是某種類型或子類型
- (BOOL)isKindOfClass:(Class)c;
TRAnimal.h
#import <Foundation/Foundation.h>
@interface TRAnimal : NSObject
-(void)eat;
@end
TRAnimal.m
#import "TRAnimal.h"
@implementation TRAnimal
-(void)eat{
NSLog(@"動物具備吃的能力");
}
@end
TRDog.h
#import "TRAnimal.h"
@interface TRDog : TRAnimal//繼承了TRAnimal
@end
TRDog.m
TRPerson.h
#import <Foundation/Foundation.h>
@interface TRPerson : NSObject//沒有繼承了TRAnimal
@end
TRPerson.m
main.m
#import <Foundation/Foundation.h>
#import "TRAnimal.h"
#import "TRDog.h"
#import "TRPerson.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRAnimal *animal = [[TRDog alloc]init];
TRAnimal *animal2 = [[TRPerson alloc]init];
Class c = [TRAnimal class];//向類發送class消息,能夠建立類對象
TRAnimal *animals[2] = {animal,animal2};
for (int i = 0; i<2; i++) {
//判斷一個對象 是不是某系列類型
if ([animals[i] isKindOfClass:c]) {
[animals[i] eat];
}
}
}
return 0;
}
結果:
動物具備吃的能力
2.判斷一個引用(實例)指向的對象是不是某種類型
-(BOOL)isMemberOfClass:(Class)c;
3.比較「類」信息的時候,須要使用類對象,判斷一個類是不是另外一個類的子類
+(BOOL)isSubclassOfClass:(Class)c;
main.m
@autoreleasepool {
TRAnimal *animal = [[TRDog alloc]init];
TRAnimal *animal2 = nil;
Class c = [TRAnimal class];
//判斷TRPerson是不是TRAnimal的子類
//健壯性
if ([TRPerson isSubclassOfClass:c]) {
NSLog(@"TRPerson是TRAnimal的子類,可使用多態");
animal2 = [[TRPerson alloc]init];
}else{
NSLog(@"TRPerson不是TRAnimal的子類,不可使用多態");
}
}
結果:
TRPerson不是TRAnimal的子類,不可使用多態
4.方法選擇器
1.能夠獲得一個方法的引用。
SEL sel = @selector(study)//方法名
2.須要判斷類中是否有某個方法
BOOL b = [TRStudent instancesRespondToSelector:@selector(study)];
3. 能夠向對象發送任何消息,而不須要在編譯的時候聲明
[stu performSelector:sel];
例:
TRAnimal.h
#import <Foundation/Foundation.h>
@interface TRAnimal : NSObject
-(void)eat;
@end
TRAnimal.m
#import "TRAnimal.h"
@implementation TRAnimal
-(void)eat{
NSLog(@"nihao");
}
@end
main.m
#import <Foundation/Foundation.h>
#import "TRAnimal.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRAnimal *animal = [[TRAnimal alloc]init];
//表明一個方法
SEL sel = @selector(eat);
//判斷一個類是否能夠響應某個消息
//判斷一個類是否有某個方法
BOOL isRespond = [TRAnimal instancesRespondToSelector:sel];
if (isRespond) {
NSLog(@"類中有eat消息,能夠發送");
//[animal eat];
}else{
NSLog(@"類中沒有eat消息,不能夠發送");
}
[animal performSelector:sel];
}
return 0;
}
結果:
類中有eat消息,能夠發送
nihao
5.協議選擇器
1.協議的引用指向一個協議
Prtocol* p = @protocol(NSCopying);
2.能夠判斷一個類是否遵照了某個協議
BOOL b = [TRStudent conformsToProtocol:p];
#import <Foundation/Foundation.h>
#import "TRProtocol.h"
#import "TRMyclass.h"
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
// id<TRProtocol> p1=[[TRStudent alloc]init];
// [p1 eat];
Protocol*p=@protocol(TRProtocol);//協議名
if ([TRStudent conformsToProtocol:p]) {
NSLog(@"遵照了協議");
}
else{
NSLog(@"沒有遵照協議");
}
}
return 0;
}
結果:
遵照了協議
=======================================================================
知識點
2、NSString
1、不可變字符串(NSString)
在新建立對象的基礎上修改,就是又複製了一份
//建立字符串
NSString *str = @"hello";
NSString *str2 = @"hello";
NSLog(@"str addr:%p",str);
NSLog(@"str2 addr:%p",str2);
//將C語言中的字符串 轉換成OC的字符串
NSString *str3 = [[NSString alloc]initWithCString:"hello"];
NSLog(@"str3 addr:%p",str3);
NSString *str4 = [[NSString alloc]initWithString:@"hello"];
NSLog(@"str4 addr:%p",str4);
//printf("%sworld","Hello");
NSString *str5 = [[NSString alloc]initWithFormat:@"%@",@"hello"];
結果:
str addr:0x100002060
str2 addr:0x100002060
str3 addr:0x100200d00
str4 addr:0x100002060
str5 addr:0x10010cd80
1.NSString的截取
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString * p=@"HelloWord";
NSString*p2=[p substringToIndex:5];//取頭(從頭到哪),to不包括下標內容
NSString*p3=[p substringFromIndex:5];//去尾(從哪到尾),from包括下標內容
NSLog(@"p2:%@ p3:%@",p2,p3);
NSRange r={4,3};//取中間,從哪長度是多少
NSString*p4=[p substringWithRange:r];
NSLog(@"p4:%@",p4);
}
return 0;
}
結果:
p2:Hello p3:Word
p4:oWo
練習:
//練習:230119197007010000
//求:年、月、日
//截取獲得日期
NSString *sid = @"230119197007010000";
//在OC當中 建立結構有更簡單的方式
//會有結構體函數解決這個問題
//NSMakeRange
NSRange range2 = NSMakeRange(6, 8);
NSString *date = [sid substringWithRange:range2];
NSLog(@"date:%@",date);
NSString *year = [date substringToIndex:4];
NSLog(@"year:%@",year);
NSString *month = [date substringWithRange:NSMakeRange(4, 2)];
NSLog(@"month:%@",month);
NSString *day = [date substringFromIndex:6];
NSLog(@"day:%@",day);
date:19700701
year:1970
month:07
day:01
2.字符串的拼接(初始化、追加、追加指定範圍)
//字符串的拼接
NSString *str10 = @"Hello";
//追加
NSString *str11 = [str10 stringByAppendingString:@"World"];
NSLog(@"str11:%@",str11);
//初始化
NSString *str12 = @"Hello";
NSString *str13 = @"World";
NSString *str14 = [NSString stringWithFormat:@"%@%@",str12,str13];
NSString *str15 = [NSString stringWithFormat:@"Hello%@",str13];
NSLog(@"str14:%@",str14);
NSLog(@"str15:%@",str15);
//按指定格式(範圍)追加內容
NSString *str16 = @"Hello";
NSString *str17 = [str16 stringByAppendingFormat:@"%@%@",@"World",@"123"];
NSLog(@"str17:%@",str17);
結果:
str11:HelloWorld
str14:HelloWorld
str15:HelloWorld
str17:HelloWorld123
3.字符串替換
//替換
NSString *str18 = @"www.tarena.com.cn";
NSString *str19 = [str18 stringByReplacingCharactersInRange:NSMakeRange(4, 6) withString:@"163"];
NSLog(@"str19:%@",str19);
結果:
str19:www.163.com.cn
4.字符串的編碼集
經過文件內容建立字符串,注意存在編碼集的問題,默認爲 ASC(不包含中文),要指定相應的中文編碼集(GBK簡體中文、 GB2312簡體中文、BIG5繁體中文、UTF8全世界主流語言...)
參數1 文件的路徑
參數2 指定文件的編碼集
參數3 出現異常處理
//編碼集
//參數 文件的路徑 不包括文件名
NSString *path = @"/Users/tarena/Desktop";
//path = [path stringByAppendingString:@"/test.txt"];
path = [path stringByAppendingString:@"/test2.rtf"];
//把文件中的內容 讀取到字符串中
//NSString *str20 = [[NSString alloc]initWithContentsOfFile:path];
NSString *str21 = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8 StringEncoding error:nil];
NSLog(@"str21:%@",str21);
5.字符串比較
BOOL b=[str isEqualToString:stu2]//stu和stu2比較,比較的是字符串的內容
注:==只能夠比較兩個字符串的地址
main.m
@autoreleasepool {
NSString* use=@"fcp";
NSString* use1=@"fcp";
NSString*password=@"123";
NSString*password1=@"123";
if ([use isEqualToString:use1]&&[password isEqualToString:password1]) {
NSLog(@"登錄成功");
}
else{
NSLog(@"登錄失敗");
}
}
結果:登錄失敗
2、可變字符串(NSMutableString)
是NSString的子類,NSString的功能都繼承,對字符串的修改是在原字符串的基礎上
c語言對象(數據)改變 CRUD 建立 查看 修改 刪除
oc數據改變 添加 刪除 替換
1.可變字符串的建立
//字符串的建立
//在可變字符串中 空字符串就有意義
NSMutableString *mString = [[NSMutableString alloc]init];
//可變字符串不能夠與代碼區的字符串賦值使用
//NSMutableString *mString2 = @"Hello";mString2將退化成NSString
//能夠指定字符串的空間大小 建立字符串
NSMutableString *mString3 =[NSMutableString stringWithCapacity:30];
2.添加內容(插入)
參數1:添加的內容
參數2:替換的長度
//可變字符串 添加內容
NSMutableString *mString4 = [[NSMutableString alloc]initWithString:@"Hello"];
[mString4 appendString:@"World"];//給mString4拼接
NSLog(@"mString4:%@",mString4);
//能夠在指定位置 添加字符串內容
[mString4 insertString:@"123" atIndex:5];
NSLog(@"mString4:%@",mString4);
結果:
mString4:HelloWorld
mString4:Hello123World
3.刪除內容
//刪除內容
NSMutableString *mString5 = [[NSMutableString alloc]initWithString:@"I am learning Objective-C language."];
//查找字符串內容,在所在字符串中的位置
NSRange range = [mString5 rangeOfString:@"learn"];//須要刪除的內容
NSLog(@"range: loc:%lu length:%lu",range.location,range.length);
//刪除可變字符串中指定的內容
[mString5 deleteCharactersInRange:range];
NSLog(@"mString5:%@",mString5);
結果:
range: loc:5 length:5
mString5:I am ing Objective-C language.
3.替換內容
參數1:(位置,長度)
參數2:替換內容
//替換內容
NSMutableString *mString6 = [[NSMutableString alloc]initWithString:@"HelloWorld!"];
[mString6 replaceCharactersInRange:NSMakeRange(4, 3) withString:@"1234"];
NSLog(@"mString6:%@",mString6);
結果:
mString6:Hell1234rld!
======================================================================================
知識點
3、類型轉換(NSNumber)
在不少類使用的時候,若是使用數值,就須要將數值轉換成對象類型
1.int類型的轉換
1.封裝方法
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithUnsignedInt:(unsigned int)value;
2.拆封方法
- (int)intValue;
- (unsigned int)unsignedIntValue;
例:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
int i=10;
//封裝 將基本數據類型封裝成數值對象類型
NSNumber* number=[NSNumber numberWithInt:i];
NSLog(@"%@",number);
//拆封
int i2=[number intValue];
NSLog(@"%d",i2);
}
return 0;
}
結果:
10
10
2.chan類型轉換
1.封裝方法
+ (NSNumber *)numberWithChar:(char)value;
+ (NSNumber *)numberWithUnsignedChar:(unsigned char)value;
2.拆封方法
- (char)charValue;
- (unsigned char)unsignedCharValue;
3.float類型轉換
4.double類型轉換
5.BOOL類型轉換
1.封裝方法
+ (NSNumber *)numberWithBool:(BOOL)value;
2.拆封方法
- (BOOL)boolValue;
========================================================================
知識點
4、NSValue
1.有時須要建立一個對象,以密切反應原始數據類型或者數 據結構,這種狀況就須要使用NSValue類,它能夠將任何 C中有效的變量類型封裝成對象類型。
2. NSNumber是NSValue的子類
1.將自定義類型轉換
經過NSValue類,將結構類型封裝成NSValue對象
參數1 結構體變量的內存地址
參數2 內存地址對應的結構體類型
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
//定義一個結構體類型
typedef struct{
int x;
int y;
}TRPoint;
//c語言中自動義數據類型 聲明一個結構變量而且賦值
TRPoint point={6,5};
//封裝成OC語言中的對象類型
//經過NSValue類,將結構類型封裝成NSValue對象
NSValue* value=[NSValue valueWithBytes:&point objCType:@encode(TRPoint)];
//解封 參數1 參數2
TRPoint point2;
[value getValue:&point2];
NSLog(@"x:%d y:%d",point2.x,point2.y);
}
return 0;
}
結果:x:6 y:5
=====================================================================================================================================
知識點
5、NSDate(日期)
NSDate存儲的是時間信息,默認存儲的是世界標準時間 (UTC),輸出時須要根據時區轉換爲本地時間。中國大陸、香 港、澳門、臺灣...的時間增均與UTC時間差爲+8,也就是 UTC+8
//日期
NSDate* date=[[NSDate alloc]init];//獲得當前時間
NSLog(@"%@",date);
NSDate* date2=[NSDate dateWithTimeIntervalSinceNow:30];//和當前比延遲30秒
NSDate* date3=[NSDate dateWithTimeIntervalSinceNow:-60*60*24];//昨天
NSDate* date4=[NSDate dateWithTimeIntervalSinceNow:60*60*24];//明天
NSLog(@"%@",date2);
NSLog(@"%@ %@",date3,date4);
結果:
2015-01-26 08:26:34 +0000今天
2015-01-26 08:27:04 +0000
2015-01-25 08:26:34 +0000昨天
2015-01-27 08:26:34 +0000明天
=====================================================================================================================================
知識點
6、NSDateFormatter
利用它能夠指定所需的任何類型的行爲, 並將指定的NSDate對象轉換成與所需行爲匹配的日期 的相應字符串表示
//轉換時間模板
NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];
//hh12小時制mm分鐘ss秒 HH24小時制 //MM月dd日yyyy年
dateFormatter.dateFormat=@"yyyy-MM-dd hh:mm:ss";
//時間對象的轉換
NSDate* date=[[NSDate alloc]init];
NSString*strDate=[dateFormatter stringFromDate:date];
NSLog(@"%@",strDate);
結果:
2015-01-26 04:48:30
練習:年齡 = 當前時間 - 出生年
根據身份證號 獲得一我的的年齡
230110197007010000
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSDate *now = [NSDate date];
//建立時間模板對象
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//指定模板格式
//yyyy MM dd hh mm ss 年月日時分秒
//formatter.dateFormat = @"hh小時mm分鐘ss秒 yyyy-MM-dd";
formatter.dateFormat = @"yyyy";
//轉換時間 按指定格式轉換時間 轉換本地時間
NSString *strDate = [formatter stringFromDate:now];
NSLog(@"strDate:%@",strDate);
//練習:年齡 = 當前時間 - 出生年
//根據身份證號 獲得一我的的年齡
//230110197007010000
NSString *sid = @"230119199907010000";
//在OC當中 建立結構有更簡單的方式
//會有結構體函數解決這個問題
//NSMakeRange
NSRange range2 = NSMakeRange(6, 8);
NSString *date = [sid substringWithRange:range2];
NSLog(@"date:%@",date);
NSString *year = [date substringToIndex:4];
int nowDate = [strDate intValue];
int idDate = [year intValue];
int yearsOld = nowDate-idDate;
NSLog(@"age:%d",yearsOld);
}
return 0;
}
結果:
strDate:2015
date:19990701
age:16
====================================================================================================================================
知識點
7、集合類(Collections)
一.NSSet
1.是一個無序的,管理多個對象的集合類,最大特色 是集合中不容許出現重複對象,和數學上的集合含義是一 樣的
2.除了無序、不準重複以外,其它功能和NSArray是同樣的
二.NSArray
1.數組是一組有序的集合,
2.經過索引下標取到數組中的各個元素,與字符串相同,
3.數組也有可變數組 (NSMutableArray)和不可變數組(NSArray),
4.數組中不能夠保存基本數據類型、結構體數據類型,須要使用 NSNumber和NSValue進行數據「封裝
1.NSArray的建立(4種)
1.普通字符串數組
NSString* str1=@"one";
NSString* str2=@"two";
NSString* str3=@"three";
NSArray* array1=[[NSArray alloc]initWithObjects:str1,@"two",str3,nil];//保存的都是地址
NSLog(@"%@",array1);
結果:
(
one,
two,
three
)
2.數組值是對象
**若是須要輸出對象時,輸出對象的屬性值,要本身重寫description方法
TRMyClass.h
#import <Foundation/Foundation.h>
@interface TRMyClass : NSObject
@property(nonatomic,assign)int i;
@property(nonatomic,copy)NSString *str;
@end
TRMyClass.m
#import "TRMyClass.h"
@implementation TRMyClass
//要本身重寫description方法
-(NSString *)description{
return [NSString stringWithFormat:@"i:%d str:%@",self.i,self.str];
}
@end
main.m
NSString *str1 = @"one";
TRMyClass *myClass = [[TRMyClass alloc]init];
myClass.i = 10;
myClass.str = @"ABC";
NSLog(@"myClass:%@",myClass);
//若是須要輸出對象時,輸出對象的屬性值,要本身重寫description方法
NSString *str2 = @"two";
NSString *str3 = @"three";
//int array[3] = {1,2,3};
NSArray *array2 = [[NSArray alloc]initWithObjects:@"one",str2,str3,myClass, nil];
NSLog(@"array2:%@",array2);
結果:
array2:(
one,
two,
three,
"i:10 str:ABC"
)
3.經過一個以有的數組 建立一個新的數組
//經過一個以有的數組 建立一個新的數組
NSArray *array3 = [[NSArray alloc]initWithArray:array2];array2是上邊的數組
NSLog(@"array3:%@",array3);
結果:同上
4.二維數組
//數組中的元素還能夠是對象(數組自己也是對象)
//二維數組
NSArray *array4 = [NSArray arrayWithObject:array2];
結果:同上
5.數組添加元素,元素爲數組
NSArray *array = @[@"one",@"two",@"three"];
//@1->[NSNumber numberWithInt:1]
//@基本數據類型->引用類型
NSArray *array2 = @[@'c',@2,@3,@YES];
//添加"一個"數組元素
NSArray *array3 = [array arrayByAddingObject:array2];
NSLog(@"array3:%@",array3);
//添加"一組"元素
NSArray *array4 = [array arrayByAddingObjectsFromArray:array2];
NSLog(@"array4:%@",array4);
結果:
array3:( 做爲一個元素
one,
two,
three,
(
99,
2,
3,
1
)
)
array4:( 成爲其中一個對象
one,
two,
three,
99,
2,
3,
1
)
2.數組的遍歷
//數組的遍歷
//array2.count == [array2 count]求數組的長度 array2是上邊的數組
for (int i = 0; i<[array2 count]; i++) {
//array[]
if (i==2) {
continue;
}
id obj = [array2 objectAtIndex:i];//經過下標獲得數組
NSLog(@"obj:%@",obj);
}
結果:
obj:one
obj:two
obj:i:10 str:ABC
**3.OC中遍歷數組方式
a、c語言中的遍歷方式
b、快速枚舉OC
參數1:每次獲得數組中元素的引用
參數2:哪個集合/組合(數組引用對象)
c、迭代器遍歷OC
能夠獲得數組或集合相應的替代器
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSArray *array = [NSArray arrayWithObjects:@"one",@"two",@"three", nil];
//1.C語言中的遍歷方式
for (int i = 0; i<[array count]; i++) {
NSLog(@"array[%d]:%@",i,[array objectAtIndex:i]);
}
//2.***快速枚舉
//參數1 每次獲得數組中元素的引用
//參數2 哪個集合/組合
for (NSString *str in array) {
NSLog(@"str:%@",str);
}
//3.迭代器遍歷
//能夠獲得數組或集合相應的替代器
NSEnumerator *enumertator = [array objectEnumerator];
//獲得迭代器指向的內存空間的引用
//而且會自動向下移動一位,當超出數組或集合的範圍則返回nil值
//[enumertator nextObject];
NSString *str = nil;
while (str = [enumertator nextObject]) {
NSLog(@"str2:%@",str);
}
//重構 學生與學校的故事
}
return 0;
}
str:one
str:two
str:three
練習:
學校和學生的故事
根據條件 篩選
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//學生
TRStudent *stu1 = [TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent *stu2 = [TRStudent studentWithAge:22 andName:@"li"];
TRStudent *stu3 = [TRStudent studentWithAge:19 andName:@"zhaoliu"];
TRStudent *stu4 = [TRStudent studentWithAge:19 andName:@"wangwu"];
TRStudent *stu5 = [TRStudent studentWithAge:20 andName:@"qianqi"];
TRStudent *stu6 = [TRStudent studentWithAge:21 andName:@"guanyu"];
TRStudent *stu7 = [TRStudent studentWithAge:20 andName:@"zhangfei"];
TRStudent *stu8 = [TRStudent studentWithAge:18 andName:@"liubei"];
//建立班級
NSArray *class1412A = [NSArray arrayWithObjects:stu1,stu2, nil];
NSArray *class1412B = [NSArray arrayWithObjects:stu3,stu4, nil];
NSArray *class1412C = [NSArray arrayWithObjects:stu5,stu6, nil];
NSArray *class1412D = [NSArray arrayWithObjects:stu7,stu8, nil];
//學院
NSArray *college3G = [NSArray arrayWithObjects:class1412A,class1412B, nil];
NSArray *collegeTest = [NSArray arrayWithObjects:class1412C,class1412D, nil];
//學校
NSArray *universityTarena = [NSArray arrayWithObjects:college3G,collegeTest, nil];
NSLog(@"universityTarena:%@",universityTarena);
//遍歷
//學校
for (int i = 0; i<[universityTarena count]; i++) {
NSArray *college =[universityTarena objectAtIndex:i];
//學院
for (int j = 0; j<[college count]; j++) {
NSArray *class = [college objectAtIndex:j];
//班級
for (int k = 0; k<[class count]; k++) {
TRStudent *stu = [class objectAtIndex:k];
//根據條件進行輸出篩選
//根據年齡進行篩選等於18
if ([stu.name isEqualToString:@"zhangsan"]) {
NSLog(@"stu name:%@ age:%d",stu.name,stu.age);
}
}
}
}
}
return 0;
}
結果:
universityTarena:(
(
(
"age:18 name:zhangsan",
"age:22 name:li"
),
(
"age:19 name:zhaoliu",
"age:19 name:wangwu"
)
),
(
(
"age:20 name:qianqi",
"age:21 name:guanyu"
),
(
"age:20 name:zhangfei",
"age:18 name:liubei"
)
)
)
stu name:zhangsan age:18
**oc中數組遍歷嵌套
//迭代器
NSEnumerator *enumerator=[university objectEnumerator];
NSArray *str=nil;
while (str=[enumerator nextObject]) {
//學院
NSEnumerator *enumerator1=[str objectEnumerator];
NSArray *str2=nil;
while (str2=[enumerator1 nextObject]) {
//班級
NSEnumerator *enumerator2=[str2 objectEnumerator];
TRStudent *str3=nil;
while (str3=[enumerator2 nextObject]) {
NSLog(@"%@",str3);
}
}
}
=====================================================================
//枚舉遍歷
for (NSArray* stu11 in university) {
for (NSArray* stu22 in stu11) {
//NSArray*class=stu22;
for (TRStudent* stu33 in stu22) {
NSLog(@"%@",stu33);
}
}
}
======================================================================================
***快速枚舉與迭代器在執行的過程當中不能直接刪除元素,須要把元素先保存起來,需等到枚舉結束,才能夠刪除
TRStudent *s=nil;
for ( TRStudent* a in class) {
if ([a.name isEqualToString:@"lisi"]) {
s=a;
//[class removeObject:a];不能夠直接在枚舉中刪除
NSLog(@"%@",a);
}
}
[class removeObject:s];
NSLog(@"%@",class);
**當數組中有多個元素重複,使用此方法
NSMutableArray *removeStrs = [NSMutableArray array];
for (NSString *str in array) {
if ([str isEqualToString:@"two"]) {
//臨時保存要刪除的內容
[removeStrs addObject:str];
}
NSLog(@"str:%@",str);
}
//[array removeObject:removeStr];
for (NSString *removeStr in removeStrs) {
[array removeObject:removeStr];
}
NSLog(@"array:%@",array);
3.查詢某個對象在數組中的位置
//返回數組中最後一個對象
id lastObj = [array2 lastObject];
NSLog(@"lastObj:%@",lastObj);
//查詢某個對象在數組中的位置
NSUInteger index = [array2 indexOfObject:str3];array2是上邊的數組
NSLog(@"index:%lu",index);
//經過下標獲得數組
NSString* objStr=[array1 objectAtIndex:0];
//求數組長度
NSUInteger l=[stus count];
NSLog(@"%lu",(unsigned long)l);
結果:
lastObj:i:10 str:ABC
index:2
練習:
如今有一些數據,它們是整型數據十、字符型數據 ‘a’、單精度浮點型數據10.1f和自定義類TRStudent的一 個對象,將它們存放在數組NSArray中
TRStudent.h
TRStudent.m
main.m
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//轉換成數值對象
NSNumber* num1=[NSNumber numberWithInt:10];
NSNumber* num2=[NSNumber numberWithChar:'a'];
NSNumber* num3=[NSNumber numberWithFloat:10.1f];
NSLog(@"%@ %@ %@",num1,num2,num3);
TRStudent* stu=[[TRStudent alloc]init];
//遍歷數組
NSArray* array=[[NSArray alloc]initWithObjects:num1,num2,num3,stu, nil];
for (int i=0; i<[array count]; i++) {
id job=[array objectAtIndex:i];
NSLog(@"%@",job);
}
}
return 0;
}
3、Ordered(數組排序)
1.排序規則本質(系統默認升序,如需降序,在NSOrderedAscending前加個減號)
’NSString *str = @"aad";
NSString *str2 = @"aac";
NSComparisonResult cr = [str compare:str2];
switch (cr) {
case NSOrderedAscending:
NSLog(@"str<str2");
break;
case NSOrderedSame:
NSLog(@"str=str2");
break;
case NSOrderedDescending:
NSLog(@"str>str2");
break;
}
結果:str>str2
2.排序規則
NSString *str11 = @"1";
NSString *str12 = @"5";
NSString *str13 = @"3";
NSArray *array = [NSArray arrayWithObjects:str11,str12,str13, nil];
NSLog(@"array:%@",array);
//排序規則
SEL cmp = @selector(compare:);
//獲得排好序的新數組
NSArray *array2 = [array 結果:
array:(
1,
5,
3
)
array2:(
1,
3,
5
)
練習1:向數組中放入數字8 3 2 1 5 進行排序
NSNumber *num1 = [NSNumber numberWithInt:8];
NSNumber *num2 = [NSNumber numberWithInt:3];
NSNumber *num3 = [NSNumber numberWithInt:2];
NSNumber *num4 = [NSNumber numberWithInt:1];
NSNumber *num5 = [NSNumber numberWithInt:5];
NSArray *array3 = [NSArray arrayWithObjects:num1,num2,num3,num4,num5, nil];
NSLog(@"array3:%@",array3);
NSArray *array4 = [array3 sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"array4:%@",array4);
結果:
array4:(
1,
2,
3,
5,
8
)
練習2:建立一個自定義類TRStudent,爲該類生成五個對象。 把這五個對象存入一個數組當中,而後按照姓名、年齡對五個對象 進行排序。
TRStudent.h
#import <Foundation/Foundation.h>
@interface TRStudent : NSObject
@property(nonatomic,assign)int age;
@property(nonatomic,copy)NSString *name;
-(id)initWithAge:(int)age andName:(NSString*)name;
+(TRStudent*)studentWithAge:(int)age andName:(NSString*)name;
//排序規則
//比較年齡
-(NSComparisonResult)compare:(TRStudent*)otherStudent;
//比較姓名
-(NSComparisonResult)compareName:(TRStudent *)otherStudent;
//先年齡後姓名
-(NSComparisonResult)compareAgeAndName:(TRStudent *)otherStudent;
@end
TRStudent.m
#import "TRStudent.h"
@implementation TRStudent
-(id)initWithAge:(int)age andName:(NSString*)name{
self = [super init];
if (self) {
self.age = age;
self.name = name;
}
return self;
}
+(TRStudent*)studentWithAge:(int)age andName:(NSString*)name{
return [[TRStudent alloc]initWithAge:age andName:name];
}
-(NSString *)description{
return [NSString stringWithFormat:@"age:%d name:%@",self.age,self.name];
}
//制定年齡的比較規則
//按姓名比較?
//若是年齡相同再按姓名比較?
//若是姓名相同再按年齡比較?
-(NSComparisonResult)compare:(TRStudent*)otherStudent{
if(self.age>otherStudent.age){
return NSOrderedDescending;
}else if (self.age == otherStudent.age){
return NSOrderedSame;
}else{
return NSOrderedAscending;
}
}
-(NSComparisonResult)compareName:(TRStudent *)otherStudent{
return [self.name compare:otherStudent.name];
}
-(NSComparisonResult)compareAgeAndName:(TRStudent *)otherStudent{
//先比較年齡
if(self.age>otherStudent.age){
return NSOrderedDescending;
}else if (self.age == otherStudent.age){
//比較姓名
return [self.name compare:otherStudent.name];
}else{
return NSOrderedAscending;
}
}
@end
main.m
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRStudent *stu1 = [TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent *stu2 = [TRStudent studentWithAge:22 andName:@"li"];
TRStudent *stu3 = [TRStudent studentWithAge:19 andName:@"zhaoliu"];
TRStudent *stu4 = [TRStudent studentWithAge:19 andName:@"wangwu"];
TRStudent *stu5 = [TRStudent studentWithAge:20 andName:@"qianqi"];
NSArray *stus = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4,stu5, nil];
NSLog(@"stus:%@",stus);
NSArray *stus2 = [stus sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"stu2:%@",stus2);
NSArray *stus3 = [stus sortedArrayUsingSelector:@selector(compareName:)];
NSLog(@"stu3:%@",stus3);
NSArray *stus4 = [stus sortedArrayUsingSelector:@selector(compareAgeAndName:)];
NSLog(@"stu4:%@",stus4);
}
return 0;
}
結果:
stu4:(
"age:18 name:zhangsan",
"age:19 name:wangwu",
"age:19 name:zhaoliu",
"age:20 name:qianqi",
"age:22 name:li"
4、數組的拷貝
- 數組的複製分爲:
1.深拷貝(內容複製):將對象生成副本
2.淺拷貝(引用複製):僅將對象的引用計數加1
- 數組中的元素,對象的引用
TRStudent.h
#import <Foundation/Foundation.h>
@interface TRStudent : NSObject<NSCopying>
@property(nonatomic,assign)int age;
@property(nonatomic,copy)NSString*name;
-(id)initWithAge:(int)age andName:(NSString*)name;
+(TRStudent*)studentWithAge:(int)age andName:(NSString*)name;
@end
TRStudent.m
#import "TRStudent.h"
@implementation TRStudent
-(id)initWithAge:(int)age andName:(NSString*)name{
if ([super init]) {
self.age=age;
self.name=name;
}
return self;
}
+(TRStudent*)studentWithAge:(int)age andName:(NSString*)name{
return [[TRStudent alloc]initWithAge:age andName:name];
}
//重寫description方法,解決返回數值問題
/*
-(NSString *)description{
return [NSString stringWithFormat:@"age:%d name:%@",self.age,self.name];
}
*/
//遵照cope協議
-(id)copyWithZone:(NSZone *)zone{
return [[TRStudent alloc]initWithAge:self.age andName:self.name];
}
@end
main.m
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRStudent *stu1 = [TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent *stu2 = [TRStudent studentWithAge:22 andName:@"li"];
TRStudent *stu3 = [TRStudent studentWithAge:19 andName:@"zhaoliu"];
TRStudent *stu4 = [TRStudent studentWithAge:19 andName:@"wangwu"];
TRStudent *stu5 = [TRStudent studentWithAge:20 andName:@"qianqi"];
NSArray *stus = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4,stu5, nil];
NSLog(@"stus:%@",stus);
//淺拷貝 NO
/*
TRStudent *stu = [[TRStudent alloc]init];
TRStudent *stu2 = stu;
*/
NSArray *stus2 = [[NSArray alloc]initWithArray:stus copyItems:NO];//淺拷貝
NSLog(@"stus2:%@",stus2);
//深拷貝 YES
//數組的深拷貝要依賴於對象的深拷貝
//對象的深拷貝(1.NSCopying 2.copyWithZone)(須要遵照copy協議)
NSArray *stus3 = [[NSArray alloc]initWithArray:stus copyItems:YES];
NSLog(@"stus3:%@",stus3);
}
return 0;
}
結果:
(
"<TRStudent: 0x10010abc0>",
"<TRStudent: 0x1001099f0>",
"<TRStudent: 0x100109c40>",
"<TRStudent: 0x10010b350>",
"<TRStudent: 0x100109e70>"
)
(
"<TRStudent: 0x10010abc0>",
"<TRStudent: 0x1001099f0>",
"<TRStudent: 0x100109c40>",
"<TRStudent: 0x10010b350>",
"<TRStudent: 0x100109e70>"
)
(
"<TRStudent: 0x100500d60>",
"<TRStudent: 0x1005004b0>",
"<TRStudent: 0x1005004d0>",
"<TRStudent: 0x1005004f0>",
"<TRStudent: 0x1005002a0>"
)
=====================================================================================================
重寫description方法,解決返回數值問題
-(NSString *)description{
return [NSString stringWithFormat:@"age:%d name:%@",self.age,self.name];
}
================================================================================================================================================================================
知識點
8、NSMutableArray(可變數組)
1.NSMutableArray(可變數組)
是Objective-C定義的可修改數組類
– 是NSArray的子類
2.建立數組
NSMutableArray* array=[NSMutableArray arrayWithObjects:@"one",@"two",@"three", nil];
3.添加元素
1.在數組末尾添加對象
2.在指定位置插入對象
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray* array=[NSMutableArray arrayWithObjects:@"one",@"two",@"three", nil];
[array addObject:@"four"];//在數組末尾添加對象
NSLog(@"%@",array);
[array insertObject:@"five" atIndex:3];//插入對象
NSLog(@"%@",array);
}
return 0;
}
結果:
(
one,
two,
three,
four
)
(
one,
two,
three,
five,
four
)
4.修改元素
1.在指定位置修改元素
2.用另外一數組替換指定範圍對象
NSMutableArray* array=[NSMutableArray arrayWithObjects:@"one",@"two",@"three", nil];
[array replaceObjectAtIndex:1 withObject:@"six"];//在指定位置修改元素
NSLog(@"%@",array);
//用另外一數組替換指定範圍對象
NSMutableArray* array2=[NSMutableArray arrayWithObjects:@"1",@"2",@"3", nil];
NSRange r={2,1};
[array replaceObjectsInRange:r withObjectsFromArray:array2];
NSLog(@"%@",array);
結果:
(
one,
six,
three
)
( one,
six,
1,
2,
3
)
5.刪除元素
1.最後一個對象
[array removeLastObject];
2.指定對象
[array removeObject:@"two"];
3.指定位置對象
[array removeObjectAtIndex:2];
4.指定範圍對象
NSRange r = {1, 2};
[array removeObjectsInRange:r];
5.清空數組
[array removeAllObjects];
//刪除數組中的元素
/*1,2,3,five,four*/
[mArray removeLastObject];
NSLog(@"mArray:%@",mArray);
[mArray removeObject:@"five"];
NSLog(@"mArray:%@",mArray);
[mArray removeObjectAtIndex:1];
NSLog(@"mArray:%@",mArray);
[mArray removeObjectsInRange:NSMakeRange(0, 2)];
NSLog(@"mArray:%@",mArray);
結果:
mArray1:(
1,
2,
3,
five
)
mArray2:(
1,
2,
3
)
mArray3:(
1,
3
)
mArray4:(
)
練習:
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRStudent* stu1=[TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent* stu2=[TRStudent studentWithAge:20 andName:@"lisi"];
NSMutableArray* class=[NSMutableArray arrayWithObjects:stu1,stu2, nil];
//添加學生
TRStudent* stu3=[TRStudent studentWithAge:19 andName:@"zhaoliu"];
[class addObject:stu3];
NSLog(@"%@",class);
//刪除學生 lisi
//[class removeObjectAtIndex:0];
//遍歷數組
for (int i=0; i<[class count]; i++) {
TRStudent* stu=[class objectAtIndex:i];
if ([stu.name isEqualToString:@"lisi"]) {//篩選出學生
[class removeObject:stu];//刪除學生
NSLog(@"%@",class);
}
}
}
return 0;
}
結果:
(
"age:18 name:zhangsan",
"age:20 name:lisi",
"age:19 name:zhaoliu"
)
(
"age:18 name:zhangsan",
"age:19 name:zhaoliu"
)
6.ios6 新語法
a.ios6.0及osx10.8以後,編譯器LLVM支持。
b.初始化數據
OC:[NSArray arrayWithObject…@「a」];
OC新:@[@「a」,@「b」];
C語言:{「a」,「b」};
c.取元素的值
OC:[數組對象 objectAtIndex…];
OC新:數組對象[下標];
d.基本類型轉換數值對象
OC:@1->[NSNumber numberWithInt:1]
OC新:NSArray *array2 = @[@'c',@2,@3,@YES];
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
//初始化
NSArray *array = [NSArray arrayWithObjects:@"one",@"two",@"three", nil];
//ios6中的新語法
NSArray *array2 = @[@"one",@"two",@"three"];
//不容許將父類類型賦值給子類類型
//NSMutableArray *array3 = @[@"one",@"two",@"three"];
*將不可變數組轉換爲可變數組
//將不可變數組轉換爲可變數組
NSMutableArray *array3 =[@[@"one",@"two",@"three"]mutableCopy];
//取元素的值
NSString *str = [array objectAtIndex:0];
//ios6中的新語法
NSString *str2 = array[0];
}
return 0;
}
做業:
1.重構 使用ios6新語法 學生與學校的故事。
2.重構 使用三種遍歷方式
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//學生
TRStudent *stu1 = [TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent *stu2 = [TRStudent studentWithAge:22 andName:@"li"];
TRStudent *stu3 = [TRStudent studentWithAge:19 andName:@"zhaoliu"];
TRStudent *stu4 = [TRStudent studentWithAge:19 andName:@"wangwu"];
TRStudent *stu5 = [TRStudent studentWithAge:20 andName:@"qianqi"];
TRStudent *stu6 = [TRStudent studentWithAge:21 andName:@"guanyu"];
TRStudent *stu7 = [TRStudent studentWithAge:20 andName:@"zhangfei"];
TRStudent *stu8 = [TRStudent studentWithAge:18 andName:@"liubei"];
//班級
NSArray *class1=@[stu1,stu2];
NSArray *class2=@[stu3,stu4];
NSArray *class3=@[stu5,stu6];
NSArray *class4=@[stu7,stu8];
//學院
NSArray *college1=@[class1,class2];
NSArray *college2=@[class3,class4];
//學校
NSArray *university=@[college1,college2];
/**/
//c語言遍歷數組
for (int i=0; i<[university count]; i++) {
NSArray* college=university[i];
//學院
for (int j=0; j<[college count]; j++) {
NSArray* class="college"[j];
//班級
for (int k=0; k<[class count]; k++) {
TRStudent*stu=class[k];
NSLog(@"%@",stu);
}
}
}
/**/
//枚舉遍歷
for (NSArray* stu11 in university) {
for (NSArray* stu22 in stu11) {
//NSArray*class=stu22;
for (TRStudent* stu33 in stu22) {
NSLog(@"%@",stu33);
}
}
}
//迭代器
NSEnumerator *enumerator=[university objectEnumerator];
NSArray *str=nil;
while (str=[enumerator nextObject]) {
//學院
NSEnumerator *enumerator1=[str objectEnumerator];
NSArray *str2=nil;
while (str2=[enumerator1 nextObject]) {
//班級
NSEnumerator *enumerator2=[str2 objectEnumerator];
TRStudent *str3=nil;
while (str3=[enumerator2 nextObject]) {
NSLog(@"%@",str3);
}
}
}
}
return 0;
}
3.National類 有名稱China,擁有多個地區,有地區
Area(名稱、人口)
建立三個地區
(beijing 3000 guangzhou 2000 shanghai 2200)
顯示全部城市及人口
只顯示北京的人口
重構... ios6新語法 遍歷三種方式
TRNational.h
#import <Foundation/Foundation.h>
@interface TRNational : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,strong)NSMutableArray *areas;
@end
TRNational.m
#import "TRNational.h"
@implementation TRNational
@end
TRArea.h
#import <Foundation/Foundation.h>
@interface TRArea : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)int population;
-(id)initWithName:(NSString*)name andPopulation:(int)population;
+(id)areaWithName:(NSString*)name andPopulation:(int)population;
@end
TRArea.m
#import "TRArea.h"
@implementation TRArea
-(id)initWithName:(NSString*)name andPopulation:(int)population{
self = [super init];
if (self) {
self.name = name;
self.population = population;
}
return self;
}
+(id)areaWithName:(NSString*)name andPopulation:(int)population{
return [[TRArea alloc]initWithName:name andPopulation:population];
}
@end
main.m
#import <Foundation/Foundation.h>
#import "TRNational.h"
#import "TRArea.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRNational *n = [[TRNational alloc]init];
n.name = @"china";
//一個對象中的屬性 若是是對象,要注意默認狀況下,是不會建立的。
//聚合
n.areas = [NSMutableArray array];
TRArea *a1 = [TRArea areaWithName:@"北京" andPopulation:3000];
TRArea *a2 = [TRArea areaWithName:@"上海" andPopulation:2200];
TRArea *a3 = [TRArea areaWithName:@"廣州" andPopulation:2000];
[n.areas addObject:a1];
[n.areas addObject:a2];
[n.areas addObject:a3];
for (int i = 0; i<[n.areas count]; i++) {
TRArea *area = n.areas[i];
NSLog(@"name:%@ pop:%d",area.name,area.population);
}
}
return 0;
}
結果:
name:北京 pop:3000
name:上海 pop:2200
name:廣州 pop:2000
======================================================================================
知識點
9、NSSet
1.NSSet是一個無序的,管理多個對象的集合類,最大特色 是集合中不容許出現重複對象,和數學上的集合含義是一 樣的。
2.除了無序、不準重複以外,其它功能和NSArray是同樣的
1.NSSet的建立
TRStudent* stu1=[[TRStudent alloc]initWithAge:18 andName:@"zhangsan"];
//數值重複
TRStudent* stu2=[[TRStudent alloc]initWithAge:18 andName:@"zhangsan"];
//地址重複
TRStudent* stu3=stu1;
//建立一個集合
NSSet* set=[NSSet setWithObjects:stu1,stu2,stu3, nil];
NSLog(@"%@",set);
結果:
{(
<TRStudent: 0x100202f10>, stu3和stu1重複,只輸出一個
<TRStudent: 0x100201b70>
)}
2.hash方法(比較地址)
1.計算機默認認爲對象的hash值相同,那麼對象就相同、重複
2.在生活中,hash值相同的重複知足不了咱們的需求,須要重寫hash方法
3.hash方法重寫有兩種狀況:
1.把返回值寫死,那麼該類全部的對象均可能相同
2.把對象中的其中一個屬性值做爲返回值,屬性值相同的,對象也可能相同
3.isEqual方法(比較值)
1.若是返回值爲真 肯定兩個對象是相同的。
2.若是返回值爲假 肯定兩個對象是不相同的。
執行順序,會自動先判斷hash值,hash相同纔會自動判斷isEqual方法。
總結:
a.判斷引用是不是同一個, 是則可能相同 ,否必定不一樣
b.判斷引用的類型是否相同, 是則可能相同, 否必定不一樣,
c.判斷引用的值是否相同 ,是則必定相同 ,否必定不一樣,
TRStudent.h
#import <Foundation/Foundation.h>
@interface TRStudent : NSObject
@property(nonatomic,assign)int age;
@property(nonatomic,copy)NSString*name;
-(id)initWithAge:(int)age andName:(NSString*)name;
+(TRStudent*)studentWithAge:(int)age andName:(NSString*)name;
@end
TRStudent.m
#import "TRStudent.h"
//hash方法
@implementation TRStudent
-(NSUInteger)hash{
NSLog(@"hash方法執行了");
//return [super hash];
return 1;
}
//重寫isEqual方法
-(BOOL)isEqual:(id)object{
NSLog(@"isEqual方法執行了");
//return [super isEqual:object];
//1.自反性
if(self == object){//兩個引用指向同一個對象
return YES;
}else{
//2.類型是否相同 若是類型不相同 確定不一樣
if(![object isMemberOfClass:[TRStudent class]]){
return NO;
}else{//3.兩個對象的類型相同才比較對象的值
TRStudent *otherStu = object;
if (self.age==otherStu.age&&[self.name isEqualToString:otherStu.name]) {
return YES;
}else{
return NO;
}
}
}
return NO;
}
-(id)initWithAge:(int)age andName:(NSString*)name{
self = [super init];
if (self) {
self.age = age;
self.name = name;
}
return self;
}
+(TRStudent*)studentWithAge:(int)age andName:(NSString*)name{
return [[TRStudent alloc]initWithAge:age andName:name];
}
@end
main.m
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRStudent *stu1 = [TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent *stu2 = [TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent *stu3 = stu1;
NSSet *set = [NSSet setWithObjects:stu1,stu2,stu3, nil];
NSLog(@"set:%@",set);
}
return 0;
}
結果:
hash方法執行了
hash方法執行了
isEqual方法執行了
hash方法執行了
set:{(
<TRStudent: 0x1001027f0>
)}
知識點
10、NSMutableSet
知識點
11、NSDictionary(不可變字典)
1.爲了查找集合中的對象更快速
2.經過key(鍵)(名字),相應的value(值)。
一般來說,key的值是字符串類型,value的值是任意對象類型
3.key值是不容許重複的,value的值是能夠重複的
4.通來來說key與value的值,不容許爲空
1.NSDictionary的建立
//初始化的時候value->key
NSDictionary* dic=[NSDictionary dictionaryWithObjectsAndKeys:@1,@"one",@2,@"two",@3,@"three", nil];
//顯示的時候 key->value
NSLog(@"%@",dic);
結果:
{
one = 1;
three = 3;
two = 2;
}
2.經過key找到相應的value
//根據key值找到相應的value
NSNumber* n1=[dic objectForKey:@"one"];dic接上邊的內容
NSLog(@"n1:%@",n1);
//字典引用 新語法
NSNumber* n2=dic[@"one"];
NSLog(@"n2:%@",n2);
結果:
n1:1
n2:1
3.獲取字典中全部的value和key
//集合中全部的key
NSArray*key=[dic allKeys];
NSLog(@"%@",key);
//集合中全部的value
NSArray*v=[dic allValues];
NSLog(@"%@",v);
結果:
(
one,
two,
three
)
(
1,
2,
3
)
4.NSDictionary遍歷
//遍歷
//獲得字典中全部的key
NSArray* keys=[dic allKeys];
for (NSString* key in keys) {
//經過每個key獲得字典中的value
NSNumber* value=[dic objectForKey:key];
NSLog(@"key:%@ value:%@",key,value);
}
結果:
key:one value:1
key:two value:2
key:three value:3
5.NSDictionary新語法
1.建立
NSDictionary *dict = @{@"1":stu, @"2":stu1};
NSDictionary* dic=[NSDictionary dictionaryWithObjectsAndKeys:@1,@"one",@2,@"two",@3,@"three", nil];
NSDictionary* dic2=@{@"one": @1,@"two":@2,@"three":@3};//字典引用 新語法
2.獲取
NSLog(@"%@", mdict[@"1"]);
NSNumber* n1=[dic objectForKey:@"one"];
//字典引用 新語法
NSNumber* n2=dic[@"one"];
6.對關鍵字進行排序
1.將字典中全部key值,按object所在類中的compare方法 進行排序,並將結果返回至數組,2.在Student類中添加compare方法
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRStudent *stu1 = [TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent *stu2 = [TRStudent studentWithAge:19 andName:@"lisi"];
TRStudent *stu3 = [TRStudent studentWithAge:20 andName:@"wangwu"];
TRStudent *stu4 = [TRStudent studentWithAge:21 andName:@"zhaoliu"];
NSDictionary *stus = [NSDictionary dictionaryWithObjectsAndKeys:stu1,stu1.name,stu2,stu2.name,stu3,stu3.name,stu4,stu4.name, nil];
//排序前
NSArray *allKeys = [stus allKeys];
for (NSString *key in allKeys) {
//key->value
TRStudent *stu = stus[key];
NSLog(@"name:%@ age:%d",stu.name,stu.age);
}
//排序後
***//1.排序的第一種方式 沒法對字典進行排序 只能對key進行排序
/**/
//NSArray *allKeys = [stus allKeys];取出keys值
NSArray *sortedAllKeys = [allKeys sortedArrayUsingSelector:@selector(compare:)];
for (NSString *key in sortedAllKeys) {
//key->value
TRStudent *stu = stus[key];
NSLog(@"name:%@ age:%d",stu.name,stu.age);
}
TRStudent.h
-(NSComparisonResult)compare:(TRStudent*)otherStudent{
return [self.name compare:otherStudent.name];
}
***//2.字典排序方式2 需重寫compare方法 如上
NSArray *sortedAllKeys2 = [stus keysSortedByValueUsingSelector:@selector(compare:)];
for (NSString *key in sortedAllKeys2) {
//key->value
TRStudent *stu = stus[key];
NSLog(@"name:%@ age:%d",stu.name,stu.age);
}
}
return 0;
}
7.文件操做
1.將字典內容寫入文件
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@1,@"one",@2,@"two", nil];
[dic writeToFile:@"/Users/tarena/Desktop/dic.xml" atomically:NO];
練習 :學生和書的故事,字典方法。
(優:經過班級信息能夠直接顯示學生信息、經過學院信息也能夠直接顯示學生信息)
#import <Foundation/Foundation.h>
#import "TRStudent.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//學生
TRStudent *stu1 = [TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent *stu2 = [TRStudent studentWithAge:22 andName:@"li"];
TRStudent *stu3 = [TRStudent studentWithAge:19 andName:@"zhaoliu"];
TRStudent *stu4 = [TRStudent studentWithAge:19 andName:@"wangwu"];
TRStudent *stu5 = [TRStudent studentWithAge:20 andName:@"qianqi"];
TRStudent *stu6 = [TRStudent studentWithAge:21 andName:@"guanyu"];
TRStudent *stu7 = [TRStudent studentWithAge:20 andName:@"zhangfei"];
TRStudent *stu8 = [TRStudent studentWithAge:18 andName:@"liubei"];
//建立班級
NSArray *class1412A = [NSArray arrayWithObjects:stu1,stu2, nil];
NSArray *class1412B = [NSArray arrayWithObjects:stu3,stu4, nil];
NSArray *class1412C = [NSArray arrayWithObjects:stu5,stu6, nil];
NSArray *class1412D = [NSArray arrayWithObjects:stu7,stu8, nil];
//建立學院
NSDictionary *college3G = [NSDictionary dictionaryWithObjectsAndKeys:class1412A,@"class1412A",class1412B,@"class1412B", nil];
NSDictionary *collegeTest = [NSDictionary dictionaryWithObjectsAndKeys:class1412C,@"class1412C",class1412D,@"class1412D", nil];
//建立學校新語法
/*
NSDictionary *universityTarena = [NSDictionary dictionaryWithObjectsAndKeys:college3G,@"college3G",collegeTest,@"collegeTest", nil];
*/
NSDictionary *universityTarena = @{@"college3G":college3G,@"collegeTest":collegeTest};
//遍歷
//學校
NSArray *collegeKeys = [universityTarena allKeys];//取出全部Keys
for (NSString *collegeKey in collegeKeys) {
NSDictionary *collegeValue = [universityTarena objectForKey:collegeKey];
//if... 查看某個學院的學生信息
//遍歷學院
NSArray *classKeys = [collegeValue allKeys];
for (NSString *classKey in classKeys) {
/* 根據班級信息 顯示學生信息
if ([classKey isEqualToString:@"class1412C"]) {
NSArray *classValue = [collegeValue objectForKey:classKey];直接輸出,不須要遍歷班級便可
}
*/
NSArray *classValue = [collegeValue objectForKey:classKey];
//遍歷班級
for (TRStudent *stu in classValue) {
/* 根據姓名查詢學生信息
if ([stu.name isEqualToString:@"zhangsan"]) {
NSLog(@"name:%@ age:%d",stu.name,stu.age);
}*/
NSLog(@"name:%@ age:%d",stu.name,stu.age);
}
}
}
}
return 0;
}
===================================================================================================
知識點
12、Block代碼段
1.Block封裝了段代碼,能夠在任什麼時候候調用執行,Block能夠做爲方法的參數、方法的返回值,和傳統的函數指針類似。
2.Block與函數的區別
a.Block是OC的語法
b.Block的定義能夠寫在方法中
c.使用起來更直接,耦合度更低
d.直接用,不用聲明
3.Block的語法
a.聲明
返回值類型
Block變量名
參數
int(^Sum2)(int,int)
b.定義
返回值類型
參數
= ^int(int i,int j){
return i+j;
};
c.調用
Block變量名
Sum2(1,2);
d.自定義Block類型
Block類型
typedef void(^Block)(void);
Block b1;使用類型聲明變量
b1();Block變量纔可使用
1.Block的定義與聲明
1.聲明定義在函數外
#import <Foundation/Foundation.h>
//^block的標識 Sum是block的名字
//聲明時也能夠省略到變量i,j
//一般定義與聲明放到一塊兒
int(^Sum)(int i,int j)=^(int i,int j){
return i+j;
};
int main(int argc, const char * argv[])
{
@autoreleasepool {
int s=Sum(1,2);//block調用
NSLog(@"%d",s);
}
return 0;
}
結果:3
2.定義在函數內部
int main(int argc, const char * argv[])
{
@autoreleasepool {
//block的定義與聲明能夠放到函數內部
int(^Sum2)(int i,int j);//聲明
Sum2=^(int i,int j){//定義
return i+j;
};
int s2=Sum2(3,4);//block調用
NSLog(@"%d",s2);
}
return 0;
}
結果:7
1.Block的排序
@autoreleasepool {
TRStudent* stu1=[TRStudent studentWithAge:18 andName:@"zhangsan"];
TRStudent* stu2=[TRStudent studentWithAge:23 andName:@"lisi"];
TRStudent* stu3=[TRStudent studentWithAge:22 andName:@"wangwu"];
TRStudent* stu4=[TRStudent studentWithAge:17 andName:@"fangwu"];
NSArray* array=[NSArray arrayWithObjects:stu1,stu2,stu3,stu4, nil];
NSLog(@"%@",array);
NSArray* array2=[array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
TRStudent*stu11=obj1;//利用兩個進行比較
TRStudent*stu21=obj2;
//return [stu1.name compare:stu2.name];
NSNumber*n1=[NSNumber numberWithInt:stu11.age];
NSNumber*n2=[NSNumber numberWithInt:stu21.age];
return [n1 compare:n2];
}];
NSLog(@"%@",array2);
結果:
(
"age:18 name:zhangsan",
"age:23 name:lisi",
"age:22 name:wangwu",
"age:17 name:fangwu"
)
(
"age:17 name:fangwu",
"age:18 name:zhangsan",
"age:22 name:wangwu",
"age:23 name:lisi"
)
2.自定義Block類型
//自定義
// 返回值類型 Block是類型 參數
typedef void(^Block)(void);
Block b1;
b1=^{
NSLog(@"Block");
};//注意封號
b1();//調用
結果:
Block
做業:
1.通信錄
TelphoneInfo
name
有多個用戶
添加用戶信息addUser:(TRUserInfo*)…
刪除用戶信息->根據用戶姓名removeUserByName
查看(單) 某我的信息->根據用戶姓名
checkByName
查看(多) 全部人信息
list…
查看(多) 全部人信息->根據用戶姓名排序
sortedListByName…
用戶
UserInfo
name
telphone
show 顯示用戶信息
TRUserInfo.h
#import <Foundation/Foundation.h>
@interface TRUserInfo : NSObject
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *telphone;
@property(nonatomic,copy)NSString *email;
-(id)initWithName:(NSString *)name andTelphone:(NSString *)telphone andEmail:(NSString *)email;
+(TRUserInfo*)userInfoWithName:(NSString *)name andTelphone:(NSString *)telphone andEmail:(NSString *)email;
-(void)show;
@end
TRUserInfo.m
#import "TRUserInfo.h"
@implementation TRUserInfo
-(id)initWithName:(NSString *)name andTelphone:(NSString *)telphone andEmail:(NSString *)email{
self = [super init];
if (self) {
self.name = name;
self.telphone = telphone;
self.email = email;
}
return self;
}
+(TRUserInfo*)userInfoWithName:(NSString *)name andTelphone:(NSString *)telphone andEmail:(NSString *)email{
return [[TRUserInfo alloc]initWithName:name andTelphone:telphone andEmail:email];
}
-(void)show{
NSLog(@"name:%@ telphone:%@ email:%@",self.name,self.telphone,self.email);
}
@end
TRTelphoneInfo.h
#import <Foundation/Foundation.h>
#import "TRUserInfo.h"
@interface TRTelphoneInfo : NSObject
@property(nonatomic,copy)NSString *name;
-(id)initWithName:(NSString*)name;
+(id)telphoneInfoWithName:(NSString*)name;
//添加用戶信息
-(void)addUser:(TRUserInfo*)user;
//刪除用戶信息
-(void)removeUserByName:(NSString*)name;
//查看某我的信息
-(void)checkUserByName:(NSString*)name;
//查看全部人信息
-(void)list;
//查看全部人信息並排序
-(void)sortedListByName;
@end
TRTelphoneInfo.m
#import "TRTelphoneInfo.h"
//擴展方法 組合
@interface TRTelphoneInfo()
@property(nonatomic,strong)NSMutableArray *userInfos;
@end
@implementation TRTelphoneInfo
-(id)initWithName:(NSString*)name{
self = [super init];
if (self) {
self.name = name;
self.userInfos = [NSMutableArray array];
}
return self;
}
+(id)telphoneInfoWithName:(NSString*)name{
return [[TRTelphoneInfo alloc]initWithName:name];
}
//添加用戶信息
-(void)addUser:(TRUserInfo*)user{
[self.userInfos addObject:user];
}
//刪除用戶信息
-(void)removeUserByName:(NSString*)name{
TRUserInfo *temp = nil;
for (TRUserInfo* userInfo in self.userInfos) {
if([userInfo.name isEqualToString:name]){
temp = userInfo;
}
}
[self.userInfos removeObject:temp];
}
//查看某我的信息
-(void)checkUserByName:(NSString*)name{
BOOL isFlag = NO;
for (TRUserInfo* userInfo in self.userInfos) {
if([userInfo.name isEqualToString:name]){
//NSLog(@"name:%@ telphone:%@ email:%@",userInfo.name,userInfo.telphone,userInfo.email);
isFlag = YES;
[userInfo show];
break;
}
}
if (!isFlag) {
NSLog(@"您輸入的姓名不存在,請從新輸入!");
}
}
//查看全部人信息
-(void)list{
for (TRUserInfo* userInfo in self.userInfos) {
[userInfo show];
}
}
//查看全部人信息並排序
-(void)sortedListByName{
NSArray *sortedUserInfos = [self.userInfos sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
TRUserInfo *stu1 = obj1;
TRUserInfo *stu2 = obj2;
return [stu1.name compare:stu2.name];
}];
for (TRUserInfo* userInfo in sortedUserInfos) {
[userInfo show];
}
}
@end
main.m
#import <Foundation/Foundation.h>
#import "TRUserInfo.h"
#import "TRTelphoneInfo.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
TRUserInfo *u1 = [TRUserInfo userInfoWithName:@"zhangsan" andTelphone:@"13700000000" andEmail:@"zhangsan@163.com"];
TRUserInfo *u2 = [TRUserInfo userInfoWithName:@"lisi" andTelphone:@"13800000000" andEmail:@"lisi@163.com"];
TRUserInfo *u3 = [TRUserInfo userInfoWithName:@"wangwu" andTelphone:@"13900000000" andEmail:@"wangwu@163.com"];
TRTelphoneInfo *telphoneInfo = [TRTelphoneInfo telphoneInfoWithName:@"電信"];
//添加用戶信息
[telphoneInfo addUser:u1];
[telphoneInfo addUser:u2];
[telphoneInfo addUser:u3];
//查看全部用戶信息
//[telphoneInfo list];
//查看按姓名排序的全部用戶信息
//[telphoneInfo sortedListByName];
//查看某我的的信息 經過名字
//[telphoneInfo checkUserByName:@"lisi"];
//根據姓名 刪除某我的的信息
[telphoneInfo removeUserByName:@"lisi"];
[telphoneInfo list];
}
return 0;
}
做業2:
學生管理系統
1.建立班級
2.刪除班級
3.查詢全部班級
4.向班級中添加學生
5.查詢全部班級全部學生
6.刪除班級中的學生
7.學生有學習成績(語文、數學、英語)
8.將學生的成績排序
補充:
1.Runtime是什麼
1.是OC語言提供的一些C函數庫,這些C函數能夠在程序運行期間獲取類信息,建立對象,調用方法。。。
2.當經過Selector調用方法時,編譯器沒法確認內存中是否有問題,會有相應警告出現,能夠用如下方式取消警告。
3.OC真在在執行的時候,會先翻譯成C++/C,再轉換成彙編代碼(計算機識別的代碼)。OC非真正面向對象,而是假的面向對象。
2.NSObjectRuntime.h頭文件串的函數
NSStringFromSelector //根據方法獲取方法名
NSSelectorFromString //根據方法名獲取方法
NSStringFromClass //根據類獲取類名
NSClassFromString //根據類名獲取類
NSStringFromProtocol //根據協議獲取協議名
NSProtocolFromString //根據協議名獲取協議
NSDictionary *user = @{@"className":@"TRPerson",
@"property":@{@"name":@"zhangsan",@"gender":@"female"},
@"method":@"show"};
NSDictionary *user2 = @{@"className":@"TRPerson",
@"property":@{@"name」:@「lisi」,@「gender」:@「Male」},
@"method":@"show"};
NSArray *users = @[user,user2];
例:
@autoreleasepool {
//經過字符串信息,也能夠建立對象
NSString *className = @"TRPerson";
Class class = NSClassFromString(className);
id obj = [[class alloc]init];
NSString *methodName = @"show";
SEL method = NSSelectorFromString(methodName);
[obj performSelector:method];
NSString *name = @"zhangsan";
NSString *gender = @"male";
SEL setName = NSSelectorFromString(@"setName:");
[obj performSelector:setName withObject:name];
SEL setGenger = NSSelectorFromString(@"setGender:");
[obj performSelector:setGenger withObject:gender];
[obj performSelector:method];
//模擬動態建立對象,能夠叫反射
//根據文件中讀出來的數據 建立相應的對象
NSDictionary *user = @{@"className":@"TRPerson",
@"property":@{@"name":@"zhangsan",@"gender":@"female"},@"method":@"show"};
NSArray *users = @[user,user2];
for (NSDictionary *user in users) {
//經過運行時 獲得對象 屬性 方法
//建立一個對象 ***放到對象數組中
}
}
copy:獲得一個不可改變的對象,複製了一份。NSstring
strong:只獲得一個內存空間 NSMutableString
ARC:
NSstring 、block:copy
OC對象:strong
簡單基本數據類型、結構體: assign