您的位置:首页 > 移动开发 > Objective-C

Objective-C: Foundation——NSString、NSMutableString、NSNumber、NSValue、NSDate

2016-08-26 09:09 337 查看

1.NSString

1.1 创建方法(3种)
1.2 截取方法(3种)
1.3 拼接方法(3种)
1.4 替换方法
1.5 从文件中读入字符串


#import <Foundation/Foundation.h>
#import "CZStudent.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//创建方法
NSString *str1=[[NSString alloc]init];//创建的是空字符串,没有意义。

NSString* str2=@"Hello world";//将一个字符串对象直接赋值给str2。@是一个对象运算符,创建的都是常量对象,保存在代码区

NSString* str3=@"Hello world";//str2与str3是同一个对象,如果两个常量对象完全相同,不会创建两个对象。
NSLog(@"str2的地址:%p,str3的地址:%p",str2,str3);

int a=10;
NSString *str4=[NSString stringWithFormat:@"%@ worl! %d",@"hello",a]; //格式化创建,通过占位符吧其他类型的数据转换为字符串
NSLog(@"%@",str4);

NSString *str5=[NSString stringWithFormat:@"%@ word %d",@"hello",a];
NSLog(@"str4的地址:%p,str5的地址:%p",str4,str5);//stringWithFormat创建的对象即使内容相同,也会是完全两个不同的对象

//。。。截取方法
NSString *str6=@"abcdefghijk";
NSString *str7=[str6 substringToIndex:3];// 截取头
NSLog(@"截取头:%@",str7);

NSString *str8=[str6 substringFromIndex:8];
NSLog(@"截取尾:%@",str8);

NSString *str9=[str6 substringWithRange:NSMakeRange(4, 3)];
NSLog(@"截取中段:%@",str9);

//。。。拼接方法
NSString *str10=@"hello";
NSString *str11=@"world";
NSString *str12=[[NSString alloc]initWithFormat:@"%@%@",str10,str11]; //初始化拼接
NSLog(@"初始化拼接:%@",str12);

NSString *str13=[str10 stringByAppendingString:str12]; //追加拼接
NSLog(@"追加拼接:%@",str13);

NSString *str14=[str10 stringByAppendingFormat:@"%d %@",a,str11];//格式化拼接,会自动将数值类型转换成字符串
NSLog(@"格式化拼接:%@",str14);

//。。。替换方法
NSString *str15=@"abcdefghijkl";
NSString *str16=[str15 stringByReplacingCharactersInRange:NSMakeRange(4, 4) withString:(@"000")];
NSLog(@"替换方法:%@",str16);

//。。。用@输出自定义类对象
CZStudent *stu=[[CZStudent alloc]initWithName:@"小明" andGender:YES andAge:18 andAdress:@"台湾"];
[stu show];
NSLog(@"%@",stu);

//。。。从文件中读入内容,创建字符串
NSString *str17=[NSString stringWithContentsOfFile:@"/Users/tarena/Desktop/testString" encoding: NSUTF8StringEncoding error:nil];

}
return 0;
}


运行结果

2016-08-26 08:44:24.789 cz_day20_01[679:26241] str2的地址:0x1000020f0,str3的地址:0x1000020f0
2016-08-26 08:44:24.790 cz_day20_01[679:26241] hello worl! 10
2016-08-26 08:44:24.790 cz_day20_01[679:26241] str4的地址:0x100300590,str5的地址:0x1003006a0

2016-08-26 08:44:24.790 cz_day20_01[679:26241] 截取头:abc
2016-08-26 08:44:24.790 cz_day20_01[679:26241] 截取尾:ijk
2016-
4000
08-26 08:44:24.790 cz_day20_01[679:26241] 截取中段:efg

2016-08-26 08:44:24.790 cz_day20_01[679:26241] 初始化拼接:helloworld
2016-08-26 08:44:24.790 cz_day20_01[679:26241] 追加拼接:hellohelloworld
2016-08-26 08:44:24.790 cz_day20_01[679:26241] 格式化拼接:hello10 world

2016-08-26 08:44:24.790 cz_day20_01[679:26241] 替换方法:abcd000ijkl
Program ended with exit code: 0


1.6 用占位符%@输出自定义类的对象


建一个Student类

.h文件

#import <Foundation/Foundation.h>

@interface CZStudent : NSObject
@property NSString* name;
@property BOOL gender;
@property int age;
@property NSString *adress;
-(id)initWithName:(NSString*)name andGender:(BOOL)gender andAge:(int)age andAdress:(NSString*)adress;
+(id)studentWithWithName:(NSString*)name andGender:(BOOL)gender andAge:(int)age andAdress:(NSString*)adress;
-(void)show;
@end


.m文件

@implementation CZStudent
-(id)initWithName:(NSString*)name andGender:(BOOL)gender andAge:(int)age andAdress:(NSString*)adress;
{
self = [super init];
if (self) {
self.name=name;
self.gender=gender;
self.age=age;
self.adress=adress;
}
return self;
}
+(id)studentWithWithName:(NSString *)name andGender:(BOOL)gender andAge:(int)age andAdress:(NSString *)adress
{
__autoreleasing CZStudent *stu=[[CZStudent alloc]initWithName:name andGender:gender andAge:age andAdress:adress];
return stu;
}
-(void)show
{
NSLog(@"姓名:%@,性别:%@,年龄:%d,住址:%@",self.name,self.gender?@"男":@"女",self.age,self.adress);
}

-(NSString*)description //默认方法是输出对象地址,在这里对它重写
{
NSString *str=[NSString stringWithFormat:@"姓名:%@,性别:%@,年龄:%d,住址:%@",self.name,self.gender?@"男":@"女",self.age,self.adress];
return str;
}
@end


main函数

CZStudent *stu=[[CZStudent alloc]initWithName:@"小明" andGender:YES andAge:18 andAdress:@"台湾"];
[stu show];
NSLog(@"%@",stu);


运行结果

2016-08-26 08:44:24.790 cz_day20_01[679:26241] 姓名:小明,性别:男,年龄:18,住址:台湾
2016-08-26 08:44:24.790 cz_day20_01[679:26241] 姓名:小明,性别:男,年龄:18,住址:台湾
Program ended with exit code: 0


1.7 判断两个字符串相等的方法


#import <Foundation/Foundation.h>
//从键盘中输入一个用户名和密码,与文件中保存的对比,如果相同,显示登陆成功,否则显示用户名或密码错误
int main(int argc, const char * argv[]) {
@autoreleasepool {
char z[100];
char m[100];
NSLog(@"请输入账号:");
scanf("%s",z);
NSLog(@"请输入密码:");
scanf("%s",m);
NSString* ID=[NSString stringWithFormat:@"%s",z];
NSString* password=[NSString stringWithFormat:@"%s",m];
NSString* file=[NSString stringWithContentsOfFile:@"/Users/tarena/Desktop/账号密码" encoding:NSUTF8StringEncoding error:nil];
NSString* fileID;
NSString* filePassword;
int i=0;
for(i=0;[[file substringWithRange:NSMakeRange(i, 1)] isEqualToString:@" "]==NO;i++);
fileID=[file substringToIndex:i];
filePassword=[file substringFromIndex:i+1];
//isEqualToString:判断两个字符串相等的方法
if([ID isEqualToString:fileID]==YES&&[password isEqualToString:filePassword])
{
NSLog(@"登陆成功");
}
else
{
NSLog(@"账号密码错误");
}

}
return 0;
}


2.NSMutableString

2.1 是可变字符串,是NSString类的子类
2.2 创建方法(4种)
2.3 添加方法(2种)
2.4 求字符串中字符的个数,即求字符串的长度
2.5 删除方法
2.6 确定子串在整个字符串中的范围
2.7 替换方法


#import <Foundation/Foundation.h>

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

//创建方法
NSMutableString *str1 =[[NSMutableString alloc]init]; //空字符串,有意义
NSMutableString *str2=[NSMutableString stringWithCapacity:100]; //预估值
//  NSMutableString *str3=@"abc";  //str3会退化成不可变字符串,不能这样初始化可变字符串
NSMutableString *str4=[NSMutableString stringWithString:@"string"];//创建可变字符串的对象同时,进行初始化的方法
NSMutableString *str5=[NSMutableString stringWithFormat:@"age:%d",6];//创建可变字符串对象的同时进行格式化初始化的方法

//添加方法
[str2 appendString:@"The word,string,"];  //追加添加方法
NSLog(@"追加添加方法:%@",str2);
[str2 appendString:@"has 6 characters"];
NSLog(@"追加添加方法%@",str2);
NSMutableString *str6=[NSMutableString stringWithString:@"string"];
[str6 appendFormat:@"has %lu characters",str6.length];
NSLog(@"追加添加方法%@",str2);

//删除方法
NSMutableString *str7=[NSMutableString stringWithString:@"I am learning Objective-C languange"];
[str7 deleteCharactersInRange:NSMakeRange(14, 10)];  //删除方法

//确定子串在整个字符中的范围
[str7 deleteCharactersInRange:[str7 rangeOfString:@"C "]];//[str7 rangeOfString:@"Objective-C"] 确定子串在整个字符中的范围
NSLog(@"删除方法%@",str7);

//替换方法
NSMutableString *str8=[NSMutableString stringWithString:@"This is a string"];
[str8 replaceCharactersInRange:[str8 rangeOfString:@"a"] withString:@"another"];
NSLog(@"替换方法%@",str8);

}
return 0;
}


运行结果

2016-08-26 08:54:19.825 cz_day20_03[816:31156] 追加添加方法:The word,string,
2016-08-26 08:54:19.825 cz_day20_03[816:31156] 追加添加方法The word,string,has 6 characters
2016-08-26 08:54:19.826 cz_day20_03[816:3115
fb54
6] 追加添加方法The word,string,has 6 characters

2016-08-26 08:54:19.826 cz_day20_03[816:31156] 删除方法I am learning languange

2016-08-26 08:54:19.826 cz_day20_03[816:31156] 替换方法This is another string
Program ended with exit code: 0


3.NSNumber

3.1 用于将基本数据类型的数据或变量封装成OC的类
3.2 封装方法:numberWith...
3.3 拆封方法:…Value


int main(int argc, const char * argv[]) {
@autoreleasepool {
int a=10;
NSNumber *i=[NSNumber numberWithInt:a];//封装:将基本数据类型的数据,变成OC类的对象。
NSLog(@"封装:%@",i);
int b;
b=[i intValue]; //拆封:将OC类的对象,还原成基本数据类型的数据
NSLog(@"拆封:%d",b);

float f=3.14;
NSNumber *f1=[NSNumber numberWithFloat:f];
NSLog(@"封装:%@",f1);
float f2;
f2=[f1 floatValue];
NSLog(@"拆封:%g",f2);

double d=2.68;
char ch='a';
BOOL b1=YES;

NSNumber* d1=[NSNumber numberWithDouble:d];
NSLog(@"封装:%@",d1);
double d2;
d2=[d1 doubleValue];
NSLog(@"拆封:%lg",d2);

NSNumber* ch1=[NSNumber numberWithChar:ch];
NSLog(@"封装:%@",ch1);   //按SCALL码输出
char ch2;
ch2=[ch1 charValue];
NSLog(@"拆封:%c",ch2);

NSNumber* b2=[NSNumber numberWithBool:b1];
NSLog(@"封装:%@",b2);
BOOL b3;
b3=[b2 boolValue];
NSLog(@"拆封:%d",b3);

}
return 0;
}


运行结果

2016-08-26 08:57:23.506 cz_day20_04[874:32681] 封装:10
2016-08-26 08:57:23.507 cz_day20_04[874:32681] 拆封:10
2016-08-26 08:57:23.507 cz_day20_04[874:32681] 封装:3.14
2016-08-26 08:57:23.507 cz_day20_04[874:32681] 拆封:3.14
2016-08-26 08:57:23.507 cz_day20_04[874:32681] 封装:2.68
2016-08-26 08:57:23.507 cz_day20_04[874:32681] 拆封:2.68
2016-08-26 08:57:23.507 cz_day20_04[874:32681] 封装:97
2016-08-26 08:57:23.507 cz_day20_04[874:32681] 拆封:a


4.NSValue

4.1 NSValue是NSNumber的父类
4.2 用于封装结构体类型的变量


#import <Foundation/Foundation.h>

typedef struct
{
int x;
int y;
}CZPoint;

typedef struct
{
char ch;
double d;
}CZMyData;

int main(int argc, const char * argv[]) {
@autoreleasepool {
CZPoint point;
point.x=10;
point.y=20;
NSValue *value=[NSValue valueWithBytes:&point objCType:@encode(CZPoint)];   //封装
NSLog(@"封装:%@",value);

CZPoint point1={0,0};
[value getValue:&point1];  //拆封
NSLog(@"拆封:(%d,%d)",point1.x,point1.y);

CZMyData data;
data.ch='a';
data.d=3.14;
NSValue *value2=[NSValue valueWithBytes:&data objCType:@encode(CZMyData)];
NSLog(@"封装:%@",value);

CZMyData data1={'v',0};
[value2 getValue:&data1];
NSLog(@"拆封:%c,%lg",data1.ch,data1.d);

int a =10;
NSValue *value3=[NSValue valueWithBytes:&a objCType:@encode(int)];
}
return 0;
}


运行结果

2016-08-26 08:59:12.854 cz_day20_05[932:33661] 封装:<0a000000 14000000>
2016-08-26 08:59:12.855 cz_day20_05[932:33661] 拆封:(10,20)
2016-08-26 08:59:12.855 cz_day20_05[932:33661] 封装:<0a000000 14000000>
2016-08-26 08:59:12.855 cz_day20_05[932:33661] 拆封:a,3.14
Program ended with exit code: 0


5.NSDate

5.1 OC中的日期时间类
5.2 创建对象即可得到世界标准时间
5.3 本地时间,需要通过一个格式代码转换
5.4 获取指定时间
5.5 时间间隔(3种)
5.6 按指定格式输出时间
5.7 时间对比(3种)


本地时间,需要通过一个格式代码转换

创建一个LocalTime的分类,主类为NSDate

.h文件

#import <Foundation/Foundation.h>
@interface NSDate (CZLocalTime)
-(NSDate*)localTime;
+(NSDate*)localTime;
@end


.m文件

#import "NSDate+CZLocalTime.h"

@implementation NSDate (CZLocalTime)
-(NSDate *)localTime  //本地世界格式
{
NSTimeZone *zone =[NSTimeZone systemTimeZone];
NSUInteger integer=[zone secondsFromGMTForDate:[NSDate date]];
NSDate *localTime =[[NSDate date] dateByAddingTimeInterval:integer];
return localTime;

}
+(NSDate*)localTime
{
return [[NSDate alloc] localTime];
}
@end


main函数

#import <Foundation/Foundation.h>
#import "NSDate+CZLocalTime.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSDate *date =[NSDate date];
NSLog(@"时间标准时间:%@",date); //世界标准时间

NSLog(@"%@",[date localTime]);
NSLog(@"本地时间:%@",[NSDate localTime]);//本地时间

NSDate *date1=[NSDate dateWithTimeIntervalSinceNow:30];  //当前世界标准时间快30秒的时间,参数写-30就是慢30秒的时间
NSLog(@"当前时间时间快30秒:%@",date1);

NSTimeInterval seconds=[date timeIntervalSince1970];//计算机元年1970年到现在世界的时间间隔
NSLog(@"1970到现在的时间间隔:%lg",seconds);
NSDate *date2=[NSDate dateWithTimeIntervalSinceNow:-60];
seconds=[date2 timeIntervalSinceNow]; //date2时间到现在的时间间隔
NSLog(@"date2到现在的时间间隔:%lg",seconds);

NSDate *time1=[NSDate dateWithTimeIntervalSinceNow:-60*60*24];
NSDate *time2=[NSDate dateWithTimeIntervalSinceNow:60*60*24];
seconds=[time1 timeIntervalSinceDate:time2];//time1到time2的时间间隔
NSLog(@"time1到time2的时间间隔%lg",seconds);

NSDateFormatter *df= [[NSDateFormatter alloc]init];
df.dateFormat=@"yyyy年MM月dd日 HH:mm:ss EEEE"; //格式化
NSString *str=[df stringFromDate:date];//会自动转成本地时间
NSLog(@"本地时间:%@",str);

//时间对比
NSDate *time3=[NSDate dateWithTimeIntervalSinceNow:-60*60*24];  //24小时之前的时间
NSDate *time4=[NSDate dateWithTimeIntervalSinceNow:60*60*24];   //24小时之后的时间
NSDate *earlierDate =[time3 earlierDate:time4]; //获取两个时间中较为早的一个
NSLog(@"较早的时间:%@",earlierDate);
NSDate *laterDate = [time3 laterDate:time4];  //获取两个时间中较晚的一个
NSLog(@"较晚的时间:%@",laterDate);

if([time1 isEqualToDate: time2]==YES)   //判断两个时间是否相同(以纳秒为单位判断,很敏感)
NSLog(@"两个时间相同");
else NSLog(@"两个时间不同");

}
return 0;
}


运行结果

2016-08-26 09:04:57.618 cz_day20_06[997:36578] 时间标准时间:2016-08-26 01:04:57 +0000
2016-08-26 09:04:57.619 cz_day20_06[997:36578] 2016-08-26 09:04:57 +0000
2016-08-26 09:04:57.619 cz_day20_06[997:36578] 本地时间:2016-08-26 09:04:57 +0000
2016-08-26 09:04:57.619 cz_day20_06[997:36578] 当前时间时间快30秒:2016-08-26 01:05:27 +0000
2016-08-26 09:04:57.619 cz_day20_06[997:36578] 1970到现在的时间间隔:1.47217e+09
2016-08-26 09:04:57.619 cz_day20_06[997:36578] date2到现在的时间间隔:-60
2016-08-26 09:04:57.619 cz_day20_06[997:36578] time1到time2的时间间隔-172800
2016-08-26 09:04:57.619 cz_day20_06[997:36578] 本地时间:2016年08月26日 09:04:57 星期五
2016-08-26 09:29:23.750 cz_day20_06[1174:44197] 较早的时间:2016-08-25 01:29:23 +0000
2016-08-26 09:29:23.750 cz_day20_06[1174:44197] 较晚的时间:2016-08-27 01:29:23 +0000
2016-08-26 09:29:23.750 cz_day20_06[1174:44197] 两个时间不同
Program ended with exit code: 0


#import <Foundation/Foundation.h>
//从键盘输入一个身份证号码,输出身份证主人的年龄
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *ID=[NSString stringWithContentsOfFile:@"/Users/tarena/Desktop/身份证" encoding:NSUTF8StringEncoding error:nil];
NSString *year=[ID substringWithRange:NSMakeRange(6, 4)];
int age=[year intValue];
NSLog(@"%d",age);
NSDateFormatter* df=[[NSDateFormatter alloc]init];
df.dateFormat=@"yyyy";
NSDate *date=[NSDate date];
NSString *thisYear=[df stringFromDate:date];
int now=[thisYear intValue];
NSLog(@"年龄是%d",now-age);

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息