(本文参考资料整理,仅作为初学笔记)
一,字符串
1.字符串字面量
NSString *a=@"this is a";
2.字符串对象初始化
NSString *aString = [[NSString alloc] initWithString:@"some string literal"];//(分配内存并初始化方法)
NSString *aString = [NSString stringWithString:@"some string literal"];(便捷方法)
3.格式化字符串
int value=3;
NSString *aString = [NSString stringWithFormat:@ "value is %d",value];
(补充:int(32位)-%d,unsigned int-%u,long(32位或64位)-%ld,unsigned long-%lu,float-%f,NSObject子类实例-%@)
4.对象格式说明符
NSString *aString=@"criminals";
NSString *anotherString = [NSString stringWithFormat :@"When you %@ strings,only %@ will use strings. ",@"criminalize",aString];
5.字符串比较
NSString *a=@"hello";
NSString *b=@"hello";
BOOL stringsAreEqual=([a isEqualToString:b]);
二,数字
NSNumber的使用
NSNumber *aNumber = [NSNumber numberWithInt:3];
NSLog(@"I have %@ apples",aNumber);
NSLog(@"I have %d apples",[aNumber intValue]);
三,数组
1.创建NSArray对象示例
NSArray *emptyArray = [NSArray array];
NSArray *firstList=[NSArray arrayWithObjects:@"apple","bananas","milk",nil];
NSArray *secList=[[NSArray alloc] initWithObjects:@"apples",@"bananas",@"milk",nil];
NSArray *thirdList=[NSArray arrayWithArray:secList];
2.数组字面语法
NSArray *array = @[@"hello",NSApp,[NSNumber numberWithInt:3]];
3.异构数组
NSArray *array=[NSArray arrayWithObjects:@"a string",[NSNumber numberWithBool:YES],nil];
4.数组下标
NSString *str=myArray[3];
四,集合
1.集合的声明
NSSet *set=[NSSet setWithObjects:@"apples",@"milk",@"bananas"];
2.测试对象是否包含在集合中
NSSet *set=[NSSet setWithObjects:@"apples",@"milk",@"bananas"];//集合的声明
NSString *string=@"apples";
if([set containsObject:string])//测试对象是否包含在集合中
NSLog(@"YES!");
NSArray *array=[set allObjects];//赋值给数组
for(NSString *string in array){//遍历数组
NSLog(@"%@",string);
}
3.可变集合
NSMutableSet *mutableSet=[NSMutableSet setWithObjects:@"apple",@"bananas",@"milk",nil];//声明可变数组
[mutableSet intersectSet:[NSSet setWithObject:@"apple"]];//现在只有"apples"了
[mutableSet uniontSet:[NSSet setWithObject:@"apple",@"bread",@"jam",nil]];//现在有"apple","bread","jam"
[mutableSet minusSet:[NSSet setWithObject:@"bread"]];//现在有"apple","jam"
[mutableSet minusSet:[NSSet setWithObject:@"pasta"]];//没有变化
五,字典
1.使用字典
NSArray *keys=[NSArray arrayWithObjects:@"name",@"idNum",nil];
NSArray *values=[NSArray arrayWithObjects:@"Bob",[NSNumber numberWithInt:123],nil];
NSMutableSet *dic=[NSDictionary dictionaryWithObjects:values forKeys:keys];
NSLog(@"dic count :%d",[dic count]);//得到2
NSLog(@"name is:%@",[dic objectForKey:@"name"]);//得到Bob
NSLog(@"birth is:%@",[dic objectForKey:@"birth"];//得到nil
2.遍历字典
NSArray *keys=[NSArray arrayWithObjects:@"name",@"idNum",nil];
NSArray *values=[NSArray arrayWithObjects:@"Bob",[NSNumber numberWithInt:123],nil];
NSMutableSet *dic=[NSDictionary dictionaryWithObjects:values forKeys:keys];
for(NSString *key in[dic allKeys]){
NSLog(@"%@ => %@",key,[dic objectForKey:key]);
}
3.字典字面量
NSDictionary *dic=@{
@"name":NSUserName(),
@"data":[NSDate date],
@"processInfo":[NSProcessInfo processInfo]
};
4.字典下标语法
id key=......;
id value=object[key];