您的位置:首页 > 移动开发 > IOS开发

[黑马IOS自学第十四篇]Foundation框架学习

2015-12-22 02:43 525 查看
框架:由许多类,方法,函数和文档按照一定逻辑组织起来的集合
不小心修改了系统的文件,引起的错误





#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {

NSString *str1 = @"abc";
NSString *str2 = @"Abc";
NSString *str4 = @"Abc";
NSString *str3 = [NSString stringWithFormat:@"abc"];
//str3在堆区,而str1,str2在常量区
//所以 ==不能判断字符串是否相等

//不是类变量前不用加 *
//NSComparisonResult 是一个枚举类型
//compare 默认区分大小写
//NSComparisonResultresult =[str1 compare:str2 ];
//如果要区分大小写
NSComparisonResultresult =[str1 compare:str2options:NSCaseInsensitiveSearch|NSNumericSearch];
switch (result) {
case NSOrderedAscending:
NSLog(@"str1 < str2升序");
break;
case NSOrderedDescending:
NSLog(@"str1 > str2降序");
break;
case NSOrderedSame:
NSLog(@"str1 == str2相等");
break;

default:
break;
}

//常量字符串,在常量区只有一份,地址一定是一样的
if(str2 == str4){
NSLog(@"相等");
}
else{
NSLog(@"不相等");
}

//isEqualToString区分大小写的

if( [str2 isEqualToString:str4]){
NSLog(@"相等");
}
else{
NSLog(@"不相等");
}
}
return 0;
}
位枚举
常用的三个函数





#import<Foundation/Foundation.h>
//检测字符串的前缀和后缀
void qianzhuihouzhui( )
{
NSString *url = @"http://www.baidu.com";

if ([url hasPrefix:@"https://"]|[urlhasPrefix:@"http://"]){
NSLog(@"http或者https协议网站");
}
else
{
NSLog(@"不是一个http协议网址");
}

if( [url hasSuffix:@".com"]){
NSLog(@".com结尾网站");
}
else{
NSLog(@"不是.com结尾网站");
}

}
int main(intargc,const char* argv[]) {
@autoreleasepool {

//字符串的查找某个字符串在另一个字符串首次出现的位置
NSString*str1 =@"sdsaiosaaaiosbbbb";//字符串中有两个ios
NSString *str2 = @"ioss";

NSRange range = [str1 rangeOfString:str2];

//range.length 字符串的长度
//range.location 字符串首次出现的位置如果查找不到会返回一个特别大的数字
if (range.location!=NSNotFound) {
NSLog(@"%lu,%lu",range.length,range.location);

}
else{
NSLog(@"没有在%@中查找到%@",str1,str2);
}

}
return 0;
}

NSRange是一个结构体变量
#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {
NSRange range ;//结构体变量
NSRange *r ;//结构体指针

//第一种赋值方法
range.location = 3 ;
range.length = 3 ;

//结构体整体变量赋值
range = (NSRange){3,3};

//3)
NSRange r3 = {.location = 3};//此时length没有赋初始值

//4) oc新增
NSRange r4 = NSMakeRange(3,3);
//loca, len

//查看结构体变量值
NSLog(@"%ld,%ld",r4.location,r4.length);

NSString *str = NSStringFromRange(r4);
NSLog(@"%@",str);
//{3, 3}

r->length = 3;
r->location = 3;
//NSLog(@"%ld,%ld",r->location,r->length);

}
return 0;
}

//
// main.m
// NSString字符串的截取
//
// Created by CHINGWEI_MACPC on 15/12/16.
// Copyright © 2015年 itcast. All rights reserved.
//

#import<Foundation/Foundation.h>
void test(){
NSString *url = @"http://www.baidu.com";

NSString *url1 = [url substringFromIndex:5];
NSLog(@"url1 =%@",url1);
// //www.baidu.com

NSString *str2 = [url substringToIndex:5];
NSLog(@"str2 =%@",str2);
//http:

NSRange r1 = {7,13};
NSString *str3 = [url substringWithRange:r1];
NSLog(@"str3 =%@",str3);
//www.baidu.com
}
void test2()
{
NSString *str =@"<itcast>黑马程序员</itcast>";
NSUInteger loc = [str rangeOfString:@">"].location +1 ;
NSUInteger len = [str rangeOfString:@"</"].location - loc ;

NSRange r2 = {loc,len};

NSString *subStr = [str substringWithRange:r2];
NSLog(@"%@",subStr);
}
int main(intargc,const char* argv[]) {
@autoreleasepool {

//字符串替换
NSString *str = @"dsdsaaasds aasd saaa ";
NSString *str2 = [str stringByReplacingOccurrencesOfString:@"a"withString:@"*"];
NSLog(@"替换后的字符串为:%@",str2);
NSRange r2 = {0,1};
NSString *str3 = [str stringByReplacingCharactersInRange:r2withString:@""];
NSUInteger len = [str3 length];
NSRange r3 = {len-1,1};
str3 = [str3 stringByReplacingCharactersInRange:r3 withString:@""];
NSLog(@"str3去掉空格后为 \"%@\"",str3);
//替换后的字符串为:dsds***sds**sds***

NSString *s1 =@"dsdsaaasds aasd saaa ";
str3 = [s1 stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]];
NSLog(@"老师方法去掉收尾空格后 \"%@\"",str3);

}
return 0;
}

void test(){
NSString *str1 = @"150";
NSString *str2 = @"100";

//强制类型转换

int num1 = [str1 intValue];
int num2 = [str2 intValue];

int minus = num1 - num2 ;

}
int main(intargc,const char* argv[]) {
@autoreleasepool {
//oc和 c语言字符串互换

//1)c -->o
1f09f
c 对象
char *s = "zs";
NSString *str = [NSString stringWithUTF8String:s];
NSLog(@"%@",str);

//2oc--->c
NSString *str2 = @"zbz";
///Users/chingwei_macpc/Documents/Foundation框架/字符串和其他数据类型转换/main.m:34:17:Initializing 'char *' with an expression of type 'const char * _Nullable'discards qualifiers
const char*s1 = [str2 UTF8String] ;
printf("%s\n",s1);

}
return 0;
}



 



#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {
//int a a 是存在栈区
NSString*str2=@"jack";//NSString 是在常量区不可变
NSLog(@"str2=%p",str2 );
//str2=0x100001048
str2=@"rose";//NSString 是在常量区不可变
NSLog(@"str2=%p",str2 );
//str2=0x100001088
//同一个变量地址不一样常量一样就存在一个内存区
//字符串所占的空间和字符串都不能改变

//[NSMutableString stringWithFormat:@"jack"]存入堆区
//字符串在内存占用的空间是不固定,并且存储内容可以被修改
NSMutableString *str1 = [NSMutableStringstringWithFormat:@"jack"];

NSLog(@"str1=%p",str1);
//str1=0x100204290

[str1 appendFormat:@"rose"];//格式化添加
NSLog(@"%@=%p",str1,str1);
//str1=0x100204290

NSMutableString *s2 =[NSMutableString string];
NSString *s3=@"itcast";
for (inti = 0; i<10; i++) {
[s2 appendString:s3];
}
NSLog(@"%@",s2);

}
return 0;
}

#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {

//append格式化添加字符串
NSMutableString *str = [NSMutableStringstring];
[str appendFormat:@"http://www.baidu.com"];
NSLog(@"%@",str);

//因为是可变的不需要void返回值

//删除字符串的某一个范围
[str deleteCharactersInRange:NSMakeRange(5, 2)];
NSLog(@"%@",str);
//http:www.baidu.com

//插入一个字符串
[str insertString:@"\\\\" atIndex:5];
NSLog(@"%@",str);

//替换字符串的一部分内容
[str replaceCharactersInRange:NSMakeRange(11, 5)withString:@"itcast"];
NSLog(@"%@",str);
//http:\\www.itcast.com

//易犯错误
//1)@"sd"是NSString
NSMutableString *test = @"sd";
///Users/chingwei_macpc/Documents/Foundation框架/NSMutableString常用方法/main.m:37:26: Incompatible pointertypes initializing 'NSMutableString *' with an expression of type 'NSString *'
NSLog(@"%@",test);
//[test appendFormat:@"asd"];
//给常量值赋值报错

//2).
NSMutableString *test1 =[NSMutableStringstring];
str.string =@"";//用空覆盖
[str appendFormat:@"xxxxxx"];
NSLog(@"%@",test1);
//输出为空

//3).到底用NSMutableString还是NSString
//特殊处理的时候字符串拼接,替换等才用到NSMUtableString

}
return 0;
}

位枚举



 
NSArray
OC中数组类,C语言只能存放一种类型数据,不能很方便的动态添加数组元素,不能方便动态的删除数组元素(长度固定)
NSArray只能存放任意oc对象,并且顺序的,不能存储非oc对象
比如int/float/double/char/enum/struct
一旦初始化完毕,它里面的内容永远固定的

#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {

//创建一个空数组
NSArray *arr1 =[NSArray array];

//创建一个数组,只有元素;
NSArray * arr2 =[NSArray arrayWithObject:@"1"];

//创建数组,有多个元素常见写法
NSArray *arr3 = [NSArray arrayWithObjects:@"1",@"2",@"3",@4,nil];

//调用对象方法创建数组 nil表示赋值结束,但不存储nil
NSArray *arr4 = [[NSArray alloc] initWithObjects:@"1",[NSNullnull],@"2",@"3",nil];

//用一个数组可以创建另外一个数组
NSArray *arr5 = [NSArray arrayWithArray:arr3];

}
return 0;
}
NSArray常见用法
void test(){
NSArray *arr =[NSArray arrayWithObjects:@"1",@"2",@"3",nil];

//获得数组长度
NSLog(@"%ld",arr.count);//3

//获取下标对应的对象
NSLog(@"%@",[arr objectAtIndex:2]);

//返回元素下标
NSUInteger loc = [arr indexOfObject:@"2"];
NSLog(@"%ld",loc);

//数组中是否包含了此元素
if ([arr containsObject:@"2"]) {
NSLog(@"包含元素@\"2\"");
}
else
{
NSLog(@"不包含");
}
}
int main(intargc,const char* argv[]) {
@autoreleasepool {
//简化的方式定义数组
NSArray *arr =@[@"1",@"2",@"3",@4,@"One"];

NSString *st1 = arr[1];
NSLog(@"%@",st1);

}
return 0;
}
数组遍历
#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {
NSArray *arr =@[@"1st",@"2nd",@"3rd",@4,@"5th"];

//遍历1通过下标访问
for (inti = 0 ; i < arr.count; i ++) {
NSLog(@"arr[%d] -> %@",i,arr[i]);
}

//遍历2快速枚举法 for循环增强形式
int i = 0 ;
for (NSString* str in arr) {

NSLog(@"arr[%d] --> %@",i,str);
i++;
}

//遍历3 block

[arr enumerateObjectsUsingBlock:^(id _Nonnullobj, NSUInteger idx, BOOL * _Nonnull stop) {
if(idx == 2)
{
*stop =YES;//停止类似break;

}
else{
NSLog(@"idx = %ld ,obj = %@",idx,obj);
}

}];
}
return 0;
}

NSArray读写文件



#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {

NSArray *arr =@[@"1st",@"2nd",@"3rd",@4,@"5th"];

//将NSArray写入到文件中

BOOL isWrite = [arr writeToFile:@"/Users/chingwei_macpc/Desktop/iosxxx.plist"atomically:YES];

if (isWrite) {
NSLog(@"写入成功");
}
else
{
NSLog(@"写入失败");
}
NSArray *readArr = [NSArrayarrayWithContentsOfFile:@"/Users/chingwei_macpc/Desktop/iosxxx.plist"];
NSLog(@"readArr= %@",readArr);

}
return 0;
}

NSArray和字符串
#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {

NSArray *arr =@[@"1st",@"2nd",@"3rd",@"4th"];

NSString *str = [arr componentsJoinedByString:@"-"];
NSLog(@"%@",str);

NSString *str2 = @"400-233-8900#400-233-3333";
//先分割#再分成两部电话
arr = [str2 componentsSeparatedByString:@"-"];
NSLog(@"%@",[arrfirstObject]);
NSLog(@"%@",[arrlastObject]);
NSLog(@"%@",arr[1]);

}
return 0;
}
NSMutableArray基本应用
#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {
//空数组
NSMutableArray *arr1 = [NSMutableArray array];
//创建一个初始化多个元素
NSMutableArray *arr2 =[NSMutableArray arrayWithObjects:@"1st", @"2nd",@"3rd",@"4th",nil];

//默认创建一个长度为5,也可以再继续扩充长度
NSMutableArray *arr3 = [NSMutableArray arrayWithCapacity:5];

//添加元素
[arr1 addObject:@"a1"];
[arr1 addObject:@"a2"];

[arr2 insertObject:@"5th" atIndex:4];
NSLog(@"%@",arr2);

//删除元素
[arr2 removeObject:@"5th"];
NSLog(@"%@",arr2);

[arr2 removeObjectAtIndex:3];
NSLog(@"%@",arr2);

//替换元素
[arr2 replaceObjectAtIndex:2 withObject:@"3three"];
NSLog(@"%@",arr2);

//查找元素
BOOL isSerach = [arr2 containsObject:@"2nd"];
NSLog(@"%d",isSerach);

//交换元素
[arr2 exchangeObjectAtIndex:0 withObjectAtIndex:2];
NSLog(@"%@",arr2);

}
return 0;
}

字典的遍历
#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {
//创建一个空字典
NSDictionary *dict1 = [NSDictionary dictionary];

//创建只有一组键值对的字典
NSDictionary*dict2 = [NSDictionarydictionaryWithObject:@"张三"forKey:@"zs"];
NSLog(@"%@",dict2);
// zs = "\U5f20\U4e09";

//创建多组键值对的字典 key和value都必须是对象
NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"k1",@"value2",@"k2",nil];

NSLog(@"%@",dict3);

//快速创建一个字典键值不能重复,如果有重复也是显示最后一个键值
NSDictionary *ditc4 = @{@"k1":@"value1",@"k2":@"value2",@"k3":@"value3"};
NSLog(@"%@",ditc4);

//打印字典的长度
NSLog(@"%ld",ditc4.count);

//根据key值取出value值
NSString *str = [ditc4 objectForKey:@"k1"];
NSLog(@"%@",str);

//字典的遍历问题
//第一步:获取所有的key
//第二步:根据key获取value
for(NSString*key in ditc4){
NSString *value =[ditc4 objectForKey:key];
NSLog(@"key= %@ ,value =%@",key,value);
}

[ditc4 enumerateKeysAndObjectsUsingBlock:^(id key,idobj, BOOL * stop) {
{
NSLog(@"key = %@ , value = %@",key,obj);
}
}];

}
return 0;
}

NSString类介绍基本使用





#import<Foundation/Foundation.h>
void test(){
//1.@""常量字符串
//atomically//原子性在写入的过程中别人是否能读
//NSUTF8StringEncodingxcode默认的文字编码格式
NSString *str =@"zhangsan李四";
NSError *err ;//错误对象
[str writeToFile:@"/Users/chingwei_macpc/desktop/1.txt"atomically:YESencoding:NSUTF8StringEncodingerror:&err];//error需要二级指针s

if (err!=nil) {
NSLog(@"写入失败!%@",err);

}

else{
NSLog(@"写入成功");
}
}
int main(intargc,const char* argv[]) {
@autoreleasepool {
test();
NSError *err ;//错误对象
NSString *str = [NSString stringWithContentsOfFile:@"/Users/chingwei_macpc/desktop/1.txt"encoding:NSUTF8StringEncodingerror:&err] ;
if (err!=nil){
NSLog(@"读取失败!%@",err);
}
else{
NSLog(@"读取成功 %@",str);
}

}
return 0;
}

NSDictionary快捷使用方式
#import<Foundation/Foundation.h>
void test(){
NSDictionary *dict4 = @{@"k1":@"value1",@"k2":@"value2",@"k3":@"value3"};

//简写形式获取key对应的value

NSLog(@"%@",dict4[@"k1"]);

//把字典保存到文件中
BOOL isWrite = [dict4 writeToFile:@"/users/chingwei_macpc/desktop/p.plist"atomically:YES];
NSLog(@"%d",isWrite);

NSDictionary *nsd = [NSDictionary dictionaryWithContentsOfFile:@"/users/chingwei_macpc/desktop/p.plist"];
NSLog(@"%@",nsd);
}

int main(intargc,const char* argv[]) {
@autoreleasepool {
668993
*ln = [NSArrayarrayWithObjects:@"大连",@"沈阳",nil];
NSArray *hb =[NSArrayarrayWithObjects:@"保定",@"石家庄",nil];

NSDictionary *dct = [NSDictionary dictionaryWithObjectsAndKeys:ln,@"ln",hb,@"hb",nil ];

NSLog(@"%@",dct);
[dct writeToFile:@"/users/chingwei_macpc/desktop/p1.plist"atomically:YES];

NSDictionary *dct1 = [NSDictionary dictionaryWithContentsOfFile:@"/users/chingwei_macpc/desktop/p1.plist" ];

[dct1 enumerateKeysAndObjectsUsingBlock:^(id key,id obj, BOOL *stop) {

for (NSString *str inobj ) {
NSLog(@"city =%@ ",str);

}
}];

//获取每个数组
NSArray * arr = dct1[@"ln"];
NSLog(@"%@",arr);
/*(
"\U5927\U8fde",
"\U6c88\U9633"
)*/
NSLog(@"%@",[arrlastObject]);//沈阳

}
return 0;
}
罗永浩用演讲赚来的钱捐给了https这个组织
NSURL其实就是我们在浏览器上看到的网站地址,这不就是一个字符串么,为什么还要在写一个NSURL呢,主要是因为网站地址的字符串都比较复杂,包括很多请求参数,这样在请求过程中需要解析出来每个部门,所以封装一个NSURL,操作很方便:
 

fileURLWithPath通过本地路径创建url文件路径
Url可以是网络路径,本地路径,其他的协议,sms,tel,https,ftp
#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {
NSString *str = @"$10000000";
NSURL *url = [NSURL URLWithString:@"file:///Users/chingwei_macpc/Desktop/3.txt"];
NSURL *url2 = [NSURL fileURLWithPath:@"sms://10086"];
NSURL *url3 = [NSURL fileURLWithPath:@"tel://10086"];
NSURL *url4 = [NSURL URLWithString:@"/Users/chingwei_macpc/Desktop/4.txt"];
if([str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil])
{
NSLog(@"写入成功");
}
if([str writeToURL:url4 atomically:YES encoding:NSUTF8StringEncoding error:nil])
{
NSLog(@"2写入成功");
}

NSString *str2 = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncodingerror:nil];
NSLog(@"str2= %@",str2);

}
return 0;
}



 

NSFileManager介绍和用法
//判断文件是否存在
NSString *filePath = @"/Users/chingwei_macpc/Desktop/3.txt";

NSString *filePath2 = @"/Users/chingwei_macpc/Desktop";

NSString *filePath3 = @"/";
//调用defaultmanager创建一个文件管理单例对象
//单利对象,程序运行期间,只有一个对象存在
NSFileManager *fm = [NSFileManager defaultManager];

BOOL isExist= [fm fileExistsAtPath:filePath];
NSLog(@"--->%d",isExist);

//判断是否在同一目录

if(isExist){
BOOL *isDir ;
[fm fileExistsAtPath:filePath2isDirectory:isDir];
if (isDir) {
NSLog(@"这是一个目录");

}
else{
NSLog(@"这不是一个目录");
}
}

//判断是否写

BOOL isYes = [fm isWritableFileAtPath:filePath3];
NSLog(@"是否可写--->%d",isYes);

//是否可读
isYes = [ fm isReadableFileAtPath:filePath3];
NSLog(@"是否可读--->%d",isYes);
//是否可删除

isYes = [fm isDeletableFileAtPath:filePath3];
NSLog(@"是否可删除--->%d",isYes);
}
return 0;
}

NSFileManager 获取文件属性和信息
NSFileManager *fm = [NSFileManager defaultManager];

NSString *filePath = @"/Users/chingwei_macpc/Desktop/3.txt";
//获取文件信息
//nil 表示错误信息不接收
NSDictionary *dict = [fm attributesOfItemAtPath:filePatherror:nil];
NSLog(@"%@",dict);

NSFileCreationDate = "2016-01-04 03:53:29+0000";
NSFileExtendedAttributes = {
"com.apple.TextEncoding" = <7574662d 383b3133 34323137 393834>;
};
NSFileExtensionHidden = 0;
NSFileGroupOwnerAccountID = 20;
NSFileGroupOwnerAccountName = staff;
NSFileHFSCreatorCode = 0;
NSFileHFSTypeCode = 0;
NSFileModificationDate ="2016-01-04 03:53:29 +0000";
NSFileOwnerAccountID = 501;
NSFileOwnerAccountName ="chingwei_macpc";
NSFilePosixPermissions = 420;
NSFileReferenceCount = 1;
NSFileSize = 9;
NSFileSystemFileNumber = 11310930;
NSFileSystemNumber = 16777220;
NSFileType = NSFileTypeRegular;
}

NSLog(@"%@,%@",[dictobjectForKey:@"NSFileOwnerAccountName"],dict[NSFileOwnerAccountName]);

chingwei_macpc,chingwei_macpc

NSFileManager *fm = [NSFileManager defaultManager];

NSString *filePath = @"/Users/chingwei_macpc/Desktop/3.txt";
NSString *subPath = @"/Users/chingwei_macpc/Desktop/music";
//获取文件信息
//nil 表示错误信息不接收
NSDictionary *dict = [fm attributesOfItemAtPath:filePatherror:nil];
NSLog(@"%@",dict);
NSLog(@"%@,%@",[dict objectForKey:@"NSFileOwnerAccountName"],dict[NSFileOwnerAccountName]);
//获得指定目录下的文件及子目录
//使用递归方式获取
NSArray *nsarr = [fm subpathsAtPath:subPath];
//NSLog(@"%@",nsarr);

//subpathsOfDirectoryAtPath不是使用递归方式
//递归方式是往栈里放,递归效率低,后进先出,如果文件多,耗性能
nsarr = [fm subpathsOfDirectoryAtPath:subPatherror:nil];
//NSLog(@"%@",nsarr);

//获取指定目录下的子目录(不在获取后代路径)
nsarr = [fm contentsOfDirectoryAtPath:subPatherror:nil];
NSLog(@"%@",nsarr);

}
return 0;

2016-01-04 23:08:35.062 nsfilemanager获取文件信息[1270:109681] {
NSFileCreationDate = "2016-01-0403:53:29 +0000";
NSFileExtendedAttributes = {
"com.apple.TextEncoding" = <7574662d 383b3133 34323137 393834>;
};
NSFileExtensionHidden = 0;
NSFileGroupOwnerAccountID = 20;
NSFileGroupOwnerAccountName = staff;
NSFileHFSCreatorCode = 0;
NSFileHFSTypeCode = 0;
NSFileModificationDate ="2016-01-04 03:53:29 +0000";
NSFileOwnerAccountID = 501;
NSFileOwnerAccountName ="chingwei_macpc";
NSFilePosixPermissions = 420;
NSFileReferenceCount = 1;
NSFileSize = 9;
NSFileSystemFileNumber = 11310930;
NSFileSystemNumber = 16777220;
NSFileType = NSFileTypeRegular;
}
2016-01-04 23:08:35.063 nsfilemanager获取文件信息[1270:109681]chingwei_macpc,chingwei_macpc
2016-01-04 23:08:35.079 nsfilemanager获取文件信息[1270:109681] (
".DS_Store",
"Avril Lavigne - Let Me Go @ GoodMorning America (5_11).mp4",
"Avril Lavigne - Live at Buffalo(NY) - My World DVD - Try to Shut Me Up Tour 2003.mp4",
"Avril Lavigne - Live in Amsterdam(Netherlands) 17_03_2003.mp4",
"Blink-182 - Live @ Red Bull SoundSpace (presented by KROQ) (2013-11-07).mp4",
"blink-182 - Live at Blizzcon 2013[FULL SHOW] HD.mp4",
"blink-182 - live in Las Vegas 2011[FULL SHOW] HD.mp4",
"GREEN DAY - ROCK AM RING 2013[LIVE HD].mp4",
"Jon Bon Jovi - Knockin' OnHeaven's Door (Mexico 1997).mp4",
kgmusic,
LP,
"One Ok Rock live in Mexico -YouTube [360p].mp4",
"querty\U6b4c\U8bcd.txt",
"ROOKiEZ is PUNK'D Street Live inIkebukuro -\U30b3\U30f3\U30d5\U309a\U30ea\U30b1\U30a4\U30b7\U30e7\U30f3\Uff08\U30a2\U30b3\U30fc\U30b9\U30c6\U30a3\U30c3\U30af\Uff09.mp4",
"Slash ft. Myles Kennedy &The Conspirators - Live at Pinkpop 2015 (Full Show) - YouTube [720p].mp4",
"Slash ft. Myles Kennedy _ TheConspirators - Live at Pinkpop 2015 (Full Show).mp4",
"Slash Max Sessions Unplugged HD -YouTube [720p].mp4",
"Velvet Revolver -Patience.mp4",
"\U5409\U4ed6",
"\U6742",
"\U77edLIVE",
"\U82f1\U96c4\U8054\U76df"
)
Program ended with exit code: 0

NSFileManager *fm = [NSFileManager defaultManager];

NSString *filePath = @"/Users/chingwei_macpc/Desktop/3.txt";
//获取文件信息
//nil 表示错误信息不接收
NSDictionary *dict = [fm attributesOfItemAtPath:filePatherror:nil];
NSLog(@"%@",dict);

NSFileCreationDate = "2016-01-04 03:53:29+0000";
NSFileExtendedAttributes = {
"com.apple.TextEncoding" = <7574662d 383b3133 34323137 393834>;
};
NSFileExtensionHidden = 0;
NSFileGroupOwnerAccountID = 20;
NSFileGroupOwnerAccountName = staff;
NSFileHFSCreatorCode = 0;
NSFileHFSTypeCode = 0;
NSFileModificationDate ="2016-01-04 03:53:29 +0000";
NSFileOwnerAccountID = 501;
NSFileOwnerAccountName ="chingwei_macpc";
NSFilePosixPermissions = 420;
NSFileReferenceCount = 1;
NSFileSize = 9;
NSFileSystemFileNumber = 11310930;
NSFileSystemNumber = 16777220;
NSFileType = NSFileTypeRegular;
}

NSLog(@"%@,%@",[dictobjectForKey:@"NSFileOwnerAccountName"],dict[NSFileOwnerAccountName]);
chingwei_macpc,chingwei_macpc

NSFileManager *fm = [NSFileManager defaultManager];

NSString *filePath = @"/Users/chingwei_macpc/Desktop/3.txt";
NSString *subPath = @"/Users/chingwei_macpc/Desktop/music";
//获取文件信息
//nil 表示错误信息不接收
NSDictionary *dict = [fm attributesOfItemAtPath:filePatherror:nil];
NSLog(@"%@",dict);
NSLog(@"%@,%@",[dict objectForKey:@"NSFileOwnerAccountName"],dict[NSFileOwnerAccountName]);
//获得指定目录下的文件及子目录
//使用递归方式获取
NSArray *nsarr = [fm subpathsAtPath:subPath];
//NSLog(@"%@",nsarr);

//subpathsOfDirectoryAtPath不是使用递归方式
//递归方式是往栈里放,递归效率低,后进先出,如果文件多,耗性能
nsarr = [fm subpathsOfDirectoryAtPath:subPatherror:nil];
//NSLog(@"%@",nsarr);

//获取指定目录下的子目录(不在获取后代路径)
nsarr = [fm contentsOfDirectoryAtPath:subPatherror:nil];
NSLog(@"%@",nsarr);

}
return 0;
2016-01-04 23:08:35.062 nsfilemanager获取文件信息[1270:109681]
{

    NSFileCreationDate = "2016-01-0403:53:29 +0000";
    NSFileExtendedAttributes =    {
       "com.apple.TextEncoding" = <7574662d 383b3133 34323137 393834>;
    };
    NSFileExtensionHidden = 0;
    NSFileGroupOwnerAccountID = 20;
    NSFileGroupOwnerAccountName = staff;
    NSFileHFSCreatorCode = 0;
    NSFileHFSTypeCode = 0;
    NSFileModificationDate ="2016-01-04 03:53:29 +0000";
    NSFileOwnerAccountID = 501;
    NSFileOwnerAccountName ="chingwei_macpc";
    NSFilePosixPermissions = 420;
    NSFileReferenceCount = 1;
    NSFileSize = 9;
    NSFileSystemFileNumber = 11310930;
    NSFileSystemNumber = 16777220;
    NSFileType = NSFileTypeRegular;
}
2016-01-04 23:08:35.063 nsfilemanager获取文件信息[1270:109681]chingwei_macpc,chingwei_macpc
2016-01-04 23:08:35.079 nsfilemanager获取文件信息[1270:109681]
(

    ".DS_Store",
    "Avril Lavigne - Let Me Go @ GoodMorning America (5_11).mp4",
    "Avril Lavigne - Live at Buffalo(NY) - My World DVD - Try to Shut Me Up Tour 2003.mp4",
    "Avril Lavigne - Live in Amsterdam(Netherlands) 17_03_2003.mp4",
    "Blink-182 - Live @ Red Bull SoundSpace (presented by KROQ) (2013-11-07).mp4",
    "blink-182 - Live at Blizzcon 2013[FULL SHOW] HD.mp4",
    "blink-182 - live in Las Vegas 2011[FULL SHOW] HD.mp4",
    "GREEN DAY - ROCK AM RING 2013[LIVE HD].mp4",
    "Jon Bon Jovi - Knockin' OnHeaven's Door (Mexico 1997).mp4",
    kgmusic,
    LP,
    "One Ok Rock live in Mexico -YouTube [360p].mp4",
    "querty\U6b4c\U8bcd.txt",
    "ROOKiEZ is PUNK'D Street Live inIkebukuro -\U30b3\U30f3\U30d5\U309a\U30ea\U30b1\U30a4\U30b7\U30e7\U30f3\Uff08\U30a2\U30b3\U30fc\U30b9\U30c6\U30a3\U30c3\U30af\Uff09.mp4",
    "Slash ft. Myles Kennedy &The Conspirators - Live at Pinkpop 2015 (Full Show) - YouTube [720p].mp4",
    "Slash ft. Myles Kennedy _ TheConspirators - Live at Pinkpop 2015 (Full Show).mp4",
    "Slash Max Sessions Unplugged HD -YouTube [720p].mp4",
    "Velvet Revolver -Patience.mp4",
    "\U5409\U4ed6",
    "\U6742",
    "\U77edLIVE",
    "\U82f1\U96c4\U8054\U76df"
)
Program ended with exit code: 0
 
NSManager增删改查
@autoreleasepool {

NSFileManager *fm = [NSFileManager defaultManager];
NSString *filePath = @"/Users/chingwei_macpc/Desktop/3.txt";
NSString *subPath = @"/Users/chingwei_macpc/Desktop/music";
NSString *createDir =@"/Users/chingwei_macpc/Desktop/aaa";
NSString *filePath2 = @"/Users/chingwei_macpc/Desktop/aaa/nsmanager.txt";
//创建文件
//路径 2.YEs/NO在创建路径的时候如果没有此路径,自己创建,NO的情况之创建最后一个目录,若前一个没有,则会报错 3.属性
BOOL isYes = [fm createDirectoryAtPath:createDirwithIntermediateDirectories:YESattributes:nilerror:nil];

if (isYes) {
NSLog(@"创建成功aaa目录成功");
}
else{
NSLog(@"目录创建失败");
}

NSString *str =@"NSSmaanger创建文件";
//nsdata 是一个处理二进制的数据的类
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
isYes = [fm createFileAtPath:filePath2contents:dataattributes:nil];
if (isYes) {
NSLog(@"创建文件--->成功");

}
else{
NSLog(@"创建文件失败");
}

//copy文件
NSString *targetPath =@"/Users/chingwei_macpc/Desktop/aaa/3.txt";
filePath = @"/Users/chingwei_macpc/Desktop/3.txt";
isYes = [fm copyItemAtPath:filePath toPath:targetPatherror:nil];
if (isYes) {
NSLog(@"拷贝文件--->成功");

}
else{
NSLog(@"拷贝文件--->失败");
}
//如何移动文件
targetPath =@"/Users/chingwei_macpc/Desktop/aaa/4.txt";
filePath = @"/Users/chingwei_macpc/Desktop/4.txt";
isYes = [fm moveItemAtPath:filePath toPath:targetPatherror:nil];
if (isYes) {
NSLog(@"移动文件文件--->成功");

}
else{
NSLog(@"移动文件--->失败");
}
//如何删除文件
filePath = @"/Users/chingwei_macpc/Desktop/aaa/4.txt";
isYes = [fm removeItemAtPath:targetPatherror:nil];
if (isYes) {
NSLog(@"删除文件--->成功");

}
else{
NSLog(@"删除文件--->失败");
}

}
 
下载文件思路
发送请求给服务器,要求下载某个文件
服务器发出响应,返回文件数据
手机通过nsdata来存放服务器返回来的数据
利用NSFileManager将,NSData里面的文件数据写到心的文件中
CreateFileAtPath

IOS沙盒机制,以及路径获取方法
IOS应用程序只能访问自己的沙盒(应用沙盒就是文件系统目录,与其他应用的文件系统隔离)
百度音乐下载的歌曲无法通过网易音乐查看,ios的iTunes也无法访问



 



Preperences偏好设置文件,可以存储2个t的文件



#import<Foundation/Foundation.h> int main(intargc,const char* argv[]) { @autoreleasepool { //沙盒根路径 NSString *sandBoxPath = NSHomeDirectory(); NSLog(@"%@",sandBoxPath); ///Users/chingwei_macpc //documents目录 NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask ,YES); NSLog(@"%@",arrayPaths); /*( "/Users/chingwei_macpc/Library/Documentation" )*/ NSString *documentPath = [arrayPaths firstObject]; NSLog(@"%@",documentPath); NSString *documentPath2 = [arrayPathslastObject]; NSLog(@"%@",documentPath2); //获取沙盒的NSLibraryDirectory arrayPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask ,YES); NSLog(@"%@",arrayPaths); // //在自己的沙盒路径创建一个文件 NSString *str = [[arrayPaths lastObject]stringByAppendingString:@"Preferences/1.txt"]; NSString *contents = @"abc"; [str writeToFile:contents atomically:YESencoding:NSUTF8StringEncodingerror:nil]; } return 0;

2016-01-05 20:41:48.791沙盒机制[954:60468] /Users/chingwei_macpc
2016-01-05 20:41:48.792沙盒机制[954:60468] (
"/Users/chingwei_macpc/Library/Documentation"
)
2016-01-05 20:41:48.793沙盒机制[954:60468] /Users/chingwei_macpc/Library/Documentation
2016-01-05 20:41:48.793沙盒机制[954:60468] /Users/chingwei_macpc/Library/Documentation
2016-01-05 20:41:48.793沙盒机制[954:60468] (
"/Users/chingwei_macpc/Library"
)
Program ended with exit code: 0

常见的结构体
@autoreleasepool {
//NSPoint是CGPoint的别名
NSPoint nsp ;
CGPoint cgp ;
nsp.x = 100 ;
nsp.y = 200 ;
cgp.x = 50 ;
cgp.y = 50 ;
NSPoint point2 = {10,20};
CGPoint point1 = {20 ,30};

//OC特有的赋值方式
CGPoint c4 = CGPointMake(4,5);
NSPoint np4 = NSMakePoint(5,6);

//CGSize 和 NSSize表示平面的面积
CGSize c5 = CGSizeMake(5,6);
NSSize s4 = NSMakeSize(5,5);

c5.width = 10 ;
c5.height = 30;

//表示平面上某个点的矩形区域 x , y, w, h
CGRect r4 = CGRectMake(4,5, 6, 7);
NSRect r2 = NSMakeRect(4,5, 6, 7);

NSRect r6 = {{4,3},{5,6}};

r4.origin.x= 0;
r4.origin.y= 0 ;
r4.size.height= 10;
r4.size.width= 10 ;
/*
struct CGRect {
CGPoint origin;
CGSize size;
};
*/

//快速查看结构体的值

NSLog(@"r4= %@",NSStringFromRect(r4));
//2016-01-05 21:12:12.808 常见结构体[1039:83930]r1 = {{0, 0}, {10, 10}}
//苹果官方推荐使用CG开头的

}
return 0;

@autoreleasepool {
//NSNumber 将int floatdouble包装成一个对象

//好处将基本的数据类型的数据,保存到数组或字典中

int a = 10 ;
NSNumber *intObj = [NSNumber numberWithInt:a];
NSMutableArray *array = [NSMutableArrayarrayWithObjects:intObj, nil];

float f1 = 29.3f;
NSNumber *floatObj = [NSNumber numberWithFloat:f1];

[array addObject:floatObj];

double d1 = 10.4;
NSNumber *doubleObj = [NSNumber numberWithDouble:d1];
[array addObject:doubleObj];

NSNumber *n1 = array[0];
int a1 = [n1 intValue];

NSNumber *n2 = array[1];
float f2 = [n2 floatValue];

NSLog(@"a1+f2=%f",a1+f2);

a1 = [array[0] intValue]+[array[1] floatValue];
NSLog(@"a1=%d",a1);

//NSNumber简写形式
[array addObject:@(a)];
[array addObject:@(f1)];
[array addObject:@(a1)];
[array addObject:@18];
[array addObject:@20.4f];
[array addObject:@9.4];
[array addObject:@YES];
NSLog(@"array=%@",array);

NSComparisonResult r1 =[array[1] compare:array[0]];
NSLog(@"r1= %ld",r1);

}
return 0;
#import<Foundation/Foundation.h>

int main(intargc,const char* argv[]) {
@autoreleasepool {

//沙盒根路径
NSString *sandBoxPath = NSHomeDirectory();
NSLog(@"%@",sandBoxPath);
///Users/chingwei_macpc

//documents目录
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask ,YES);
NSLog(@"%@",arrayPaths);

/*(
"/Users/chingwei_macpc/Library/Documentation"
)*/

NSString *documentPath = [arrayPaths firstObject];
NSLog(@"%@",documentPath);
NSString *documentPath2 = [arrayPathslastObject];
NSLog(@"%@",documentPath2);

//获取沙盒的NSLibraryDirectory
arrayPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask ,YES);
NSLog(@"%@",arrayPaths);

// //在自己的沙盒路径创建一个文件
NSString *str = [[arrayPaths lastObject]stringByAppendingString:@"Preferences/1.txt"];
NSString *contents = @"abc";
[str writeToFile:contents atomically:YESencoding:NSUTF8StringEncodingerror:nil];

}
return 0;

2016-01-05 20:41:48.791沙盒机制[954:60468] /Users/chingwei_macpc
2016-01-05 20:41:48.792沙盒机制[954:60468] (
   "/Users/chingwei_macpc/Library/Documentation"
)
2016-01-05 20:41:48.793沙盒机制[954:60468] /Users/chingwei_macpc/Library/Documentation
2016-01-05 20:41:48.793沙盒机制[954:60468] /Users/chingwei_macpc/Library/Documentation
2016-01-05 20:41:48.793沙盒机制[954:60468] (
   "/Users/chingwei_macpc/Library"
)
Program ended with exit code: 0
 
 
常见的结构体
  @autoreleasepool {
//NSPoint是CGPoint的别名
NSPoint nsp ;
CGPoint cgp ;
nsp.x = 100 ;
nsp.y = 200 ;
cgp.x = 50 ;
cgp.y = 50 ;
NSPoint point2 = {10,20};
CGPoint point1 = {20 ,30};

//OC特有的赋值方式
CGPoint c4 = CGPointMake(4,5);
NSPoint np4 = NSMakePoint(5,6);

//CGSize 和 NSSize表示平面的面积
CGSize c5 = CGSizeMake(5,6);
NSSize s4 = NSMakeSize(5,5);

c5.width = 10 ;
c5.height = 30;

//表示平面上某个点的矩形区域 x , y, w, h
CGRect r4 = CGRectMake(4,5, 6, 7);
NSRect r2 = NSMakeRect(4,5, 6, 7);

NSRect r6 = {{4,3},{5,6}};

r4.origin.x= 0;
r4.origin.y= 0 ;
r4.size.height= 10;
r4.size.width= 10 ;
/*
struct CGRect {
CGPoint origin;
CGSize size;
};
*/

//快速查看结构体的值

NSLog(@"r4= %@",NSStringFromRect(r4));
//2016-01-05 21:12:12.808 常见结构体[1039:83930]r1 = {{0, 0}, {10, 10}}
//苹果官方推荐使用CG开头的

}
return 0;

@autoreleasepool {
//NSNumber 将int floatdouble包装成一个对象

//好处将基本的数据类型的数据,保存到数组或字典中

int a = 10 ;
NSNumber *intObj = [NSNumber numberWithInt:a];
NSMutableArray *array = [NSMutableArrayarrayWithObjects:intObj, nil];

float f1 = 29.3f;
NSNumber *floatObj = [NSNumber numberWithFloat:f1];

[array addObject:floatObj];

double d1 = 10.4;
NSNumber *doubleObj = [NSNumber numberWithDouble:d1];
[array addObject:doubleObj];

NSNumber *n1 = array[0];
int a1 = [n1 intValue];

NSNumber *n2 = array[1];
float f2 = [n2 floatValue];

NSLog(@"a1+f2=%f",a1+f2);

a1 = [array[0] intValue]+[array[1] floatValue];
NSLog(@"a1=%d",a1);

//NSNumber简写形式
[array addObject:@(a)];
[array addObject:@(f1)];
[array addObject:@(a1)];
[array addObject:@18];
[array addObject:@20.4f];
[array addObject:@9.4];
[array addObject:@YES];
NSLog(@"array=%@",array);

NSComparisonResult r1 =[array[1] compare:array[0]];
NSLog(@"r1= %ld",r1);

}
return 0;



 @autoreleasepool {

//创建一个结构体变量
CGPoint c1 = CGPointMake(4,2);
//NSMutableArray*array1 = [NSMutableArray array];
NSValue *v1 = [NSValue valueWithPoint:c1];

//[array1addObject:v1];
NSMutableArray *array1 = [NSMutableArrayarrayWithObjects:v1 , nil];
CGRect r1 = CGRectMake(4, 4, 5, 5);
NSValue *v2 = [NSValue valueWithRect:r1];
[array1 addObject:v2];

//接收一个rect的nsvalue
NSValue *r1val = [array1 lastObject];
NSRect r2 = [r1val rectValue];
NSLog(@"r2 = %@",NSStringFromRect(r2));

//一般结构体
typedef structDate{
int yeat ;
int month ;
int day ;
}myDate;

myDate mydate1 ={1989,12,07};
//传送一个常量指针 后一句话作用把MyDate类型生成一个常量字符串描述
NSValue *mydateVal = [NSValue valueWithBytes:&mydate1 objCType:@encode(myDate)];
[array1 addObject:mydateVal];

NSLog(@"array= %@",array1);
//"<c5070000 0c000000 07000000>"

//从数组中取出来的NSValue对象
//在对象中,取出结构体变量的值
//传入一个结构体变量的地址
//getValue获取结构值,保存到结构体变量tmd
myDate tmd ;
[mydateVal getValue:&tmd];
NSLog(@"tmd= %d,%d,%d",tmd.yeat,tmd.month,tmd.day);
//2016-01-0522:50:59.585 NSValue[1423:127371] tmd = 1989,12,7

}
return 0;

NSDate *date2 = [NSDatedate];
NSLog(@"格林威治时间(默认时间)时间 %@",date2);//获取的时间是格林威治时间 0时区的

//设置时区
NSTimeZone * ntz = [NSTimeZone systemTimeZone];

//设置时间间隔
NSInteger interval = [ntz secondsFromGMTForDate:date2];
//重新生成时间
NSDate *localDate = [ date2 dateByAddingTimeInterval:interval];
NSLog(@"当前日期:%@",localDate);

//格式化日期
NSDateFormatter *formatter = [NSDateFormatternew];
formatter.dateFormat =@"yyyy年MM月dd日HH:mm:ss";
NSString *dateStr = [formatter stringFromDate:date2];
NSLog(@"当前时间 %@",dateStr);

//计算日期
NSTimeInterval t = 60*60*24;
NSDate *tom = [NSDate dateWithTimeIntervalSinceNow:t];
dateStr= [formatterstringFromDate:tom];
NSLog(@"明天此刻时间 %@",dateStr);

//计算昨天此刻时间
t = -60*60*24;
NSDate *yesterday = [date2 addTimeInterval:t];
//'addTimeInterval:'is deprecated: first deprecated in OS X 10.6
//过时的方法,可以使用NSDate dateWithTimeIntervalSinceNow:t]
dateStr= [formatterstringFromDate:yesterday];
NSLog(@"昨天此刻时间 %@",dateStr);

//日期对象创建一个日历对象unit单元

int unit =NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour;
NSDate *c3 = [NSDate date];
NSCalendar *ca1 = [NSCalendar currentCalendar];
NSDateComponents *ndc1 = [ca1 components:unitfromDate:c3];
NSLog(@"%ld年,%ld月,%ld日,%ld时,%ld分,%ld秒",ndc1.year,(long)ndc1.month,ndc1.day,ndc1.hour,ndc1.minute,ndc1.second);
//2016年,1月,6日,2时,8分,1秒

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateFormatter *formatter2 = [NSDateFormatternew];
//一定要有这句
formatter2.dateFormat=@"yyyy-MM-dd HH:mm:ss";
NSString *time1 = @"2014-04-0820:20:23";

NSString *time2 = @"2015-05-0821:23:23";

NSDate *c1 = [formatter2 dateFromString:time1];
NSDate *c2 = [formatter2 dateFromString:time2];

NSLog(@"c1=%@,c2=%@\n",c1,c2);
NSDateComponents *cms = [cal components:unitfromDate:c1 toDate:c2options:0];

NSLog(@"相差%ld年,%ld月,%ld日,%ld时,%ld分,%ld秒",cms.year,cms.month,cms.day,cms.hour,cms.minute,cms.second);

Person *p = [Personnew];

NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:p];
//[arr addObject:p];
[arr removeObject:p];
//如果对象从数组中移除,对象的引用计数器 -1

NSLog(@"person.retainCount=%ld",p.retainCount);

//数组被销毁
[arr release];
//array 数组中没有元素之后,对对象p没有影响

[p release];

//数组销毁的时候,对对象发送了一次release消息

//销毁顺序,数组--->数组向其中的对象也发送release

//当对象被添加到数组的时候,对象引用计数器 +1 remove开头的方法名对象,被移除的对象引用计数器 -1
//当数组销毁的时候,集合/数组会向它其中的所有元素发送一次release消息
//数组被销毁了,里面存储的对象不一定被销毁


使用copy会产生一个副本的过程。
修改源文件的内容,不会影响副本文件
修改副本的内容,不会影响源文件

oc的copy是指对象的拷贝。
作用:利用一个源对象产生一个副本对象



 



 
不可变对象,copy产生的对象也是不可变的
NSString产生的对象也只能用NSString接收

Dog *d = [Dognew];
//Dog *byd = [d copy];
//copyWithZone错误

NSString *str1 = @"abv";
NSString *str2 = [str1 copy];
NSLog(@"%@",str2);

//可变对象产生的对象也是可变的
//不管对象时否可变,只要使用mutableCopy的对象都是可变的
NSMutableString *str4 = [str1 mutableCopy];
[str4 appendString:@"xxxxxxx"];

NSLog(@"%@",str4);

/*
*** Terminating app due to uncaught exception'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object withappendString:'

*/
//copy不可变的
NSMutableString *str5 = [str1 copy];
[str5 appendString:@"xxxxxxx"];
NSLog(@"%@",str5);

}

Copy是浅复制mutableCopy是深复制
 





#import<Foundation/Foundation.h>
#import"Person.h"
int main(intargc,const char* argv[]) {
@autoreleasepool {

Person *p = [Personnew];

NSMutableString *str = [NSMutableStringstring];
[strappendString:@"张无忌"];
p.name = str;

NSLog(@"p.name=%@",p.name);

[strappendString:@"&&老顽童"];
NSLog(@"p.name=%@",p.name);

[p release];

}
return 0;
}

#import<Foundation/Foundation.h>

@interface Person :NSObject
//retain方式不能产生副本
//@property(nonatomic,retain) NSString *name;
@property (nonatomic,copy)NSString *name;
@end

#import"Person.h"

@implementation Person
- (void)dealloc
{
[_namerelease];
NSLog(@"Person对象释放");
[superdealloc];
}
@end
因为setName内部是copy计数器加1所以dealloc的方法需要release一次



 
为自定义类使用copy,遵守NSCopying协议
实现copywithzone方法,返回值是id类型,需要返回一个对象的副本
如果对象没有可变或者不可变区别,的情况,只需要实现copywithzone方法。
copywithzone的参数zone可以不去理会,历史问题



改变对象1的同时会改变对象2
在copyWithZone中修改如下
自定义的对象copy都是深复制



#import<Foundation/Foundation.h>
#import"Person.h"
int main(intargc,const char* argv[]) {
@autoreleasepool {

Person *p = [Personnew];
p.tuiNum = 10;
p.speed = 100;

Person *p1 = [p copy];
p1.tuiNum =100;
p1.speed = 300;
NSLog(@"p.tuiNum =%d,p.speed = %d;",p.tuiNum,p.speed);
NSLog(@"p1.tuiNum =%d,p1.speed = %d;",p1.tuiNum,p1.speed);

}
return 0;
}

#import<Foundation/Foundation.h>

@interface Person :NSObject<NSCopying>
@property(nonatomic,assign)int tuiNum;
@property(nonatomic,assign)int speed ;
//@property(nonatomic,copy)
@end

#import"Person.h"

@implementation Person
- (id)copyWithZone:(nullableNSZone *)zone{

NSLog(@"执行了copy方法");

Person *d = [[Person alloc] init];
d.speed =self.speed;
d.tuiNum =self.tuiNum;

return d;
}
@end

单例模式



 
单例模式下,一个类中设定了值所有类都能获取到
#import<Foundation/Foundation.h>
#import"Tools.h"
#import"Person.h"
#import"Cat.h"
#import"Dog.h"
int main(intargc,const char* argv[]) {
@autoreleasepool {
//对象在任何时候,都只有一个,好处是,在多个类之间共享数据
//设计要点:
//1.保证唯一,程序运行期间必须唯一
//2.单例类,必须提供一个接入点,特殊的类方法

Person *p = [Personnew];
[p run];

Dog *d = [Dognew];
[d run];

Cat *c = [Catnew];
[c eat];

}
return 0;
}

#import<Foundation/Foundation.h>

@interfaceTools :NSObject<NSCopying>//继承NSCopying协议
@property (nonatomic,assign)int num ;
@property (nonatomic,copy)NSString *text;
//提供一个接入点类方法
+(instancetype)shareInstances;
@end

#import"Tools.h"
//定义一个全局变量
Tools *instances =nil;
@implementationTools
+(instancetype)shareInstances{

//目的:保证对象必须唯一
if(instances ==nil){
//创建一个对象
instances = [[Tools alloc] init];
return instances;
}

return instances ;

}
+(id)allocWithZone:(struct_NSZone *)zone{

@synchronized(self) {//同一个时间只准一个对象访问,线程保护
if (instances== nil) {
instances = [super allocWithZone:zone];
return instances;
}

}
return instances;

}
-(id)copyWithZone:(nullableNSZone *)zone{

returnself ;//并没有copy直接return self

}

-(id)retain{
return self;
}
-(NSUInteger)retainCount{
return NSUIntegerMax;
}
-(onewayvoid)release{

}
-(id)autorelease{
return self;
}
@end

#import<Foundation/Foundation.h>

@interface Person :NSObject
-(void)run;
@end

#import"Person.h"
#import"Tools.h"
@implementation Person
-(void)run{

Tools *toolPerson = [Tools shareInstances];

//NSLog(@"toolPerson=%d,toolPerson=%@",toolPerson.num,toolPerson.text);

toolPerson.num = 10 ;
toolPerson.text =@"heima";
//设置

}
@end

#import<Foundation/Foundation.h>

@interface Dog :NSObject
-(void)run;
@end

#import"Dog.h"
#import"Tools.h"
@implementation Dog
-(void)run{
Tools *toolDog = [Tools shareInstances];
NSLog(@"toolDog=%d,toolDog=%@",toolDog.num,toolDog.text);

//设置
toolDog.num = 12 ;
toolDog.text =@"oooddddd";
}
@end

#import<Foundation/Foundation.h>

@interface Cat :NSObject
-(void)eat;
@end

#import"Cat.h"
#import"Tools.h"
@implementation Cat
-(void)eat{
Tools *toolCat = [[Toolsalloc]init];
//需要重新alloc才不会创建新的对象
// Tools*toolCat = [Tools shareInstances];
NSLog(@"toolCat=%d,toolCat=%@",toolCat.num,toolCat.text);
}
@end<span style="font-family: Calibri;font-size:18px; background-color: rgb(255, 255, 255);"> </span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: