iOS:常用属性、方法
前言:一段时间没接触,很容易就忘记以前的知识。专写一篇,供几个月没接触,拿起却忘记了。
0、宏定义、系统相关
0-1)、宏定义、规范
变量: //全局变量通常用小写g来提示 int gNumb=0; //宏定义通常用小写k来提示,也不一定全是 #define kMaxValue(value1,value2) ( value1>value2 ? value1 : value2 )
0-2)、系统相关
//重写父类的方法,如TableViewCell 和 按钮等本身有些View
-(void)layoutSubviews
{
[super layoutSubviews];
}
//自带set 和 get 方法
@property (nonatomic,strong) NSArray *myArr;
//重写属性(如MVC,给cell模型,数据就刷上View)
- (void)setLabelString:(NSString *)labelString
{
_labelString = labelString;
self.labelView.text = labelString;
}
//懒加载 : 用这个数组的时候才去加载它!加载完之后,不在加载!(也相当于重写上面的get方法)
-(NSArray *)myArr
{
if (_myArr==nil) {
_myArr = ;
}
return _myArr;
}
//获取本地path NSString *path = [[NSBundle mainBundle]pathForResource:@"xxx" ofType:@"mp3"]; //url连接地址 NSURL *url = [NSURL fileURLWithPath:path];
//字体样式 NSArray * array = [UIFont familyNames]; //每个样式的子样式 NSArray * subfontArr = [UIFont fontNamesForFamilyName:array[0]]; //字体粗体 UIFont *font = [UIFont boldSystemFontOfSize:20.0];
//添加观察者
[self.phone addObserver:self forKeyPath:@"price" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
//观察到变化控制
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
NSNumber *num = [change objectForKey:@"new"];
NSLog(@"%@",num);
}
//移除观察者
-(void)dealloc
{
// [self removeObserver:self forKeyPath:@"xxx"];
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
//发送通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"pricechange" object:self userInfo:nil];
//添加观察者 观察通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(salephone:) name:@"pricechange" object:nil];
//接受到通知做控制
-(void)salephone:(NSNotification*)noti
{
noti.object
}
//移除观察者
-(void)dealloc
{
// [self removeObserver:self forKeyPath:@"xxx"];
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
//回调、Block
//声明
int (^myBlock) (int a,int b);
//实现(赋值)
myBlock = ^(int a, int b){
return a+b;
};
//声明和实现放在一块
int (^myBlock) (int a,int b) = ^(int a, int b){
return a+b;
};
//调用
int result = myBlock(5,6);
NSLog(@"%d",result);
//直接给函数参数设回调类型(block参数相同即可,如可传 加、减、乘、除 不同操作的block进来)
-(void)test:(int(^)(int a,int b))myBlock
{
int res = myBlock(10,10);
}
//调用,不同上面,这里需要自己实现block的操作,如在a+b、a-b、a*b、a/b等操作
[self test:^int(int a, int b) {
}];
[self test:myBlock];
//加__block才能影响到里面
__block int num;
//定义一个回调类型,无返回值,一个参数button
typedef void(^ButtonBlock)(UIButton *button);
//谓词 NSArray *DATA_A =@[类,类,类,类,类]; //设置过滤条件 NSPredicate *newpre = [NSPredicate predicateWithFormat:@"age > 29"]; @"name BEGINSWITH 'x' " @"name ENDSWITH 'x' " @"name CONTAINS 'x' " @"age > 29 || age < 20" @"name like '?d*' " //过滤后保存的数组 NSArray *newarray = [DATA_A filteredArrayUsingPredicate:newpre];
//KeyPath @"dogs.@sum.weight" @"dogs.@avg.weight" @"dogs.@min.weight" @"dogs.@max.weight" [array valueForKeyPath:@"@sum.floatValue"]; [array valueForKeyPath:@"@avg.floatValue"]; [array valueForKeyPath:@"@max.floatValue"]; [array valueForKeyPath:@"@min.floatValue"];
1、View
1-1)View的属性
//中心点,设置中心点,就不用设置X、Y view.center //bounds 以自身为坐标系,改变是以中心为原点改变。 view.bounds = CGRectMake(0, 0, 20, 20);//只能修改大小 //frame 以父视图 view.frame = CGRectMake(100, 100, 200, 200); //背景颜色 view.backgroundColor //标签 view.tag //视图交互,可能会挡住下面的视图 view.userinteractionenabled //父视图 view.superview //超过父视图就剪切掉 view.clipstobounds //透明 view.alpha //隐藏 view.hidden //旋转一圈 view.transform = CGAffineTransformRotate(view.transform, M_PI); //宽放大1.5倍,高放大1.5倍, view.transform = CGAffineTransformScale(view.transform, 1.5, 1.5);
1-2)View的layer
//设置圆角 [view.layer setCornerRadius:100]; //设置边框 [view.layer setBorderWidth:2.0]; //设置边框的颜色 [view.layer setBorderColor:[[UIColor grayColor] CGColor]]; // 设置阴影不能 masksToBounds !!! //设置阴影透明度 [view.layer setShadowOpacity:1.0]; //设置阴影偏移,宽2,高5 [view.layer setShadowOffset:CGSizeMake(2, 5)]; //设置颜色 [view.layer setShadowColor:[[UIColor grayColor] CGColor]]; PS: //超过父视图,自动剪裁(UIImageView 和UILabel 等一些控件,需要加这句才能setCorn!) [label.layer setMasksToBounds:YES];
1-3)View的方法
//把子视图View移到最前面 [self.view bringSubviewToFront:view]; //把子视图移到最下层 [self.view sendSubviewToBack:view2]; //插入 [self.view insertSubview:view2 atIndex:1]; [self.view insertSubview:view2 aboveSubview:view1]; [self.view insertSubview:view2 belowSubview:view1]; //所有的子视图 NSArray *array= [self.view subviews]; //视图移除 [view removeFromSuperview]; //根据标签取View,宏定义 [view viewWithTag:1000];
2、UILabel
2-1)UILabel的属性
//内容 label.text //字体 label.font = [UIFont systemFontOfSize:fontSize]; //系统 label.font = [UIFont fontWithName:@"Times New Roman" size:fontSize]; //Times New Roman体 label.font = [UIFont italicSystemFontOfSize:fontSize]; //斜体 label.font = [UIFont boldSystemFontOfSize:fontSize]; //粗体 //字体默认左对齐 label.textAlignment = NSTextAlignmentLeft; //换行 label.numberOfLines = 0; //缺省模式,换行保证一个完整的单词 label.lineBreakMode = NSLineBreakByWordWrapping; //高亮模式 label.highlighted = YES; //高亮模式的字体颜色 label.highlightedTextColor = [UIColor redColor]; //阴影颜色 label.shadowColor = [UIColor greenColor]; //阴影偏移量,宽偏移5,高偏移5 label.shadowOffset = CGSizeMake(5, 5);
3、UIButton
3-1)UIButton的属性
//按钮失能 btn.enabled = NO; //按钮选中 btn.selected = YES;
3-2)UIButton的方法
//按钮创建的类方法
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//按钮是否选中状态
[button isSelected];
//设置不同状态下的【标题】,有正常、选中、失能等
[btn setTitle:@"点击" forState:UIControlStateNormal];
//设置不同状态下的【标题颜色】,有正常、选中、失能等
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//设置不同状态下的【图片】,有正常、选中、失能等
[btn setImage:[UIImage imageNamed:@"correct"] forState:UIControlStateNormal];
//设置不同状态下的【背景图片】,有正常、选中、失能等
[btn setBackgroundImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];
//按钮当前【标题】(获取用于切换视图,传值等用途)
NSString *titlenormal = [btn titleForState:UIControlStateNormal];
//按钮当前【图片】(获取用于切换视图,传Image等用途)
[btn currentImage]
//按钮当前【背景图片】(获取用于切换视图,传Image等用途)
[btn currentBackgroundImage]
//微调标题的位置(既然要调整,感觉还是用layout吧!)
[btn setTitleEdgeInsets:UIEdgeInsetsMake(20, -20, 0, 0)];
//按钮添加触摸事件
[btn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
//实现方法
-(void)clickAction:(UIButton*)button
{
NSLog(@"点击了");
}
4、UITextField
4-1)UITextField的属性
//清除模式是否一直显示 tfView.clearButtonMode = UITextFieldViewModeAlways; //自制清除模式,如密码显示与否,小眼睛 tfView.rightView = view; tfView.rightViewMode = UITextFieldViewModeAlways; //自制特定的键盘,如银行账号登录, tfView.inputView = view; tfView.inputAccessoryView = view; //键盘类型,如电话号码,不让输字母 tfView.keyboardType = UIKeyboardTypeDefault; //键盘的颜色 tfView.keyboardAppearance = UIKeyboardAppearanceDark; //边界风格 tfView.borderStyle = UITextBorderStyleRoundedRect; //内容 tfView.text = @"0";
4-2)UITextField的方法
//第一响应,切换视图后自动跳出
[tfView becomeFirstResponder];
(View的方法)
//结束编辑,如输入完成,点击其他地方,按键自动缩回
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
4、导航栏
4-1)、导航栏
//隐藏navigationBar(它推过的所有的VC共用这个Bar) self.navigationController.navigationBarHidden=YES; [self.navigationController.navigationBar setHidden:YES]; //加载提示,原生,用得少 self.navigationItem.prompt = @"加载中..."; //系统的BarButton UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:nil]; //设置左边BarButton self.navigationItem.leftBarButtonItems = @[left_Item1,backItem]; self.navigationItem.leftBarButtonItem = backItem; //设置右边BarButton self.navigationItem.rightBarButtonItem = self.editButtonItem; //navigationBar的背景颜色 self.navigationController.navigationBar.backgroundColor = [UIColor greenColor]; //代理,VC将要出现,VC出现 self.navigationController.delegate = self; //当前显示的VC self.navigationController.visibleViewController; //某个导航栏里的顶层VC self.navigationController.topViewController; //创建 UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:rootVC]; //推出新的视图,返回用POP,只有Controller才能推。View推不了 [self.navigationController pushViewController:root animated:YES]; //返回,Pop [self.navigationController popToRootViewControllerAnimated:YES]; //navigation 推过的所有VC NSArray *vcArray = [self.navigationController viewControllers]; //返回到指定的VC [self.navigationController popToViewController:vcArray[1] animated:YES]; //navigationBar的背景图片 [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"image1"] forBarMetrics:UIBarMetricsDefault]; (其他) //设置了title,会自动变成navigationBar的名字 self.title = @"表视图控制器”;
4-2)、工具栏ToolBar
//自定义工具栏 UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, WITDH, 44)]; //覆盖 [self.navigationController.toolbar addSubview:toolbar]; //隐藏 self.navigationController.toolbarHidden = NO; //填充空的地方 //Flexible 灵活,柔韧,有弹性 UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; //固定间距 UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil]; fixspace.width =120.0; //设置工具栏的BarButton toolbar.items = @[item1,fixspace,item2,fixspace,item3,fixspace,item4];
5、分栏
//分栏子控制器(主页VC)
MainViewController *mainCtr = [[MainViewController alloc]init];
//设置 title 后,会在 分栏、导航栏 显示
mainCtr.title = @"第一界面";
//分栏子控制器,在分栏显示的item,有自己的title,不再和导航栏共用
UITabBarItem *mainItem = [[UITabBarItem alloc]initWithTitle:@"首页" image:[UIImage imageNamed:@"tabbar_home"] selectedImage:[UIImage imageNamed:@"tabbar_home_selected"]];
//覆盖上去
mainCtr.tabBarItem = mainItem;
//创建分栏控制器
UITabBarController *tabBarCtr = [[UITabBarController alloc]init];
//设置子控制器
[tabBarCtr setViewControllers:@[mainCtr,shopCtr,mydetailCtr,aboutCtr,moreCtr]];
//把分栏控制器放到rootVC显示,类似的还有导航栏
self.window.rootViewController = tabBarCtr;
//选中的渲染颜色
tabBarCtr.tabBar.tintColor = [UIColor cyanColor];
//分栏的背景颜色
tabBarCtr.tabBar.barTintColor = [UIColor blackColor];
//tabbar样式
tabBarCtr.tabBar.barStyle = UIBarStyleDefault ;
//设置字体大小,样式(+appearance,改变全局属性)
[[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:13]} forState:UIControlStateNormal];
//大的背景图片
tabBarCtr.tabBar.backgroundImage = [UIImage imageNamed:@"image3"];
//选中的背景图片
tabBarCtr.tabBar.selectionIndicatorImage = [UIImage imageNamed:@"menu_tab_bak"];
//根据Index切换分栏,可以自制分栏控制器(self.tabBar.hidden)或是 中间大圆形按钮 等用途
self.selectedIndex
//超过五个界面 可以拖拽调整!
//分栏子控制器的子视图(分栏->主页->主页详情)
mainDetailViewController *mainDetail = [[mainDetailViewController alloc] init];
//当推出视图时隐藏分栏控制器
mainDetail.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:mainDetail animated:YES];
5、UIScrollView
5-1)、UIScrollView的属性
//可滑动的总宽、高 scrollView.contentSize = CGSizeMake(WIDTH*self.imgArr.count, 0); //自动分页 scrollView.pagingEnabled = YES; //反弹效果 scrollView.bounces = NO; //代理(基本要,监测滑动减速、停止) scrollView.delegate = self; //锁定方向,不能斜着拉 scrollView.directionalLockEnabled = NO; //当前偏移(可以用来设置偏移量,让scrollView滚动) scrollView.contentOffset //横向条显示 scroll.showsHorizontalScrollIndicator = NO; //竖向条显示 scroll.showsVerticalScrollIndicator = YES; //滚动使能 scroll.scrollEnabled = NO; //滚动条颜色 scroll.indicatorStyle = UIScrollViewIndicatorStyleWhite; //内边距(可做 划过导航栏半透明的效果、显示到底了、下拉加载功能) scroll.contentInset = UIEdgeInsetsMake(50, 0, 0, 0); //拖动条内边距 scroll.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 0, 0);
5-2)、UIScrollView的方法
//有动画效果的滑动
[scroll setContentOffset:CGPointMake(WIDTH, 0) animated:YES];
//代理,滑动减速(其实,这里可以直接和属性判断,下面只能区别TableView和scrollView)
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
if ([scrollView isMemberOfClass:[UIScrollView class]]) {
_pageCtr.currentPage = scrollView.contentOffset.x/WIDTH;
}
}
6、表视图
6-1)、table的属性
//表头(只有一个,组头有多个) tableView.tableHeaderView = view; //行高,默认是44 tableView.rowHeight = 100.0; //分割线风格 tableView.separatorStyle = UITableViewCellSeparatorStyleNone; //分割线颜色 tableView.separatorColor = [UIColor redColor];
6-2)、table的方法
//重载(更新数据源后,需要重载) [tableView reloadData];
6-3)、cell的属性
//内容 cell.textLabel.text = @"xxx"; //详细内容 cell.detailTextLabel.text = @"xxx"; //图片,png可以没后缀,jpg一定要有,严谨起见,最后连png也写出来吧! cell.imageView.image = [UIImage imageNamed:@"xxx"]; //点击不会有灰色的 cell.selectionStyle = UITableViewCellSelectionStyleNone; //右边的箭号 cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //自定义右边的View,最常见的情况是个箭号,表示加载更多 cell.accessoryView = view; //注意,一般添加用contentView,和Cell直接添加有点区别 [cell.contentView addSubview:view]; (这里是UILabel的属性) //不限行 = 自动换行, cell.textLabel.numberOfLines = 0; //字体样式、大小设置, cell.textLabel.font (其他相关) indexPath.row indexpath.section
6-4)、cell的自定义
6-4-1)、cell的重写父类方法
-(void)layoutSubviews
{
[super layoutSubviews];
self.imageView.frame =;
self.titleLabel.frame = ;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
}
6-4-2)、cell的重写 initWithFrame: reuseIdentifier:
7、UIPageControl
7-1)、UIPageControl的属性
//多少页(小圆点) _pageCtr.numberOfPages //当前页 _pageCtr.currentPage //小圆点的颜色 _pageCtr.pageIndicatorTintColor = [UIColor redColor]; //当前选中的小圆点的颜色 _pageCtr.currentPageIndicatorTintColor = [UIColor blueColor]; //注意!如果加在scrollView上,会跟着移没掉,要和scrollView同一个父级,初级错误。 [self.view addSubview:_pageCtr];
7-2)、UIPageControl的方法
//注意:page变化不是通过代理,而是和按钮一样:事件。
[page addTarget:self action:@selector(choosePage:) forControlEvents:UIControlEventValueChanged];
//可以通过page切换相应的界面
-(void)choosePage:(UIPageControl*)page
{
NSLog(@"%ld",page.currentPage);
}
7-3)、与scrollView连用,需要根据scroll的滑动,更新page的小圆点
参照“5-2)、UIScrollView的方法”
7、警告窗
//创建一个警告窗控制器,及名字、消息、弹窗类型
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定收藏?" preferredStyle:UIAlertControllerStyleAlert];
//警告按钮1
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
{
}];
//警告按钮2
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
{
}];
//添加警告按钮1、2
[alert addAction:action1];
[alert addAction:action2];
//弹出
[self presentViewController:alert animated:YES completion:^{
}];
8、类的自定义Copy、深拷贝
//.h签协议
<NSCopying>
//.m设置要复制的值
- (id)copyWithZone:(nullable NSZone *)zone
{
NSLog(@"复制对象调用了!");
Person *person = [[self class] allocWithZone:zone];
person.name = [_name mutableCopy];
person.age = _age;
person.bookArray = [_bookArray mutableCopy];
return person;
}
//在别的类调用
Person *person2 = [person1 copy];
9、类的自定义编码
//.h签协议
<NSCoding>
//.m
//设置要编码的值
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:NAME];
[aCoder encodeInteger:_age forKey:AGE];
[aCoder encodeObject:_hobby forKey:HOBBY];
}
//.m
//设置要解码的值
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self)
{
self.name = [aDecoder decodeObjectForKey:NAME];
self.age = [aDecoder decodeIntegerForKey:AGE];
self.hobby = [aDecoder decodeObjectForKey:HOBBY];
}
return self;
}
//在别的类调用
//地址
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/test.txt"];
//归档(编码)
[NSKeyedArchiver archiveRootObject:atext toFile:path]
//读取
[NSKeyedUnarchiver unarchiveObjectWithFile:path];
其他:
1、 重写,父类有声明,不必再声明 2、 @private 私有:只有类定义内部可访问 @protected 保护:只有类本身和子类的定义里可访问 @public 公有:程序的任何位置都可访问 3、 协议 @required @optional 4、 nonatomic copy assign
附录:
1-1、字符串:
1)、创建 1-1)、 [[NSString alloc]init]; 1-2)、类方法 [NSString stringWithString:string]; [NSString stringWithFormat:@"%@",string2]; 1-3)、对象方法 [[NSString alloc]initWithString:string]; [[NSString alloc]initWithFormat:@"%@",string1]; 2)、格式化拼接 [NSString stringWithFormat:@"%@%@",string3,string4]; 3)、比较 [string3 isEqualToString:string4]; [string3 caseInsensitiveCompare:string4]; [string3 compare:string4] 4)、长度 string.length; [string length]; 5)、大小写变化 [string uppercaseString]; [string lowercaseString]; [string capitalizedString]; 6)、追加 [string4 stringByAppendingString:string3]; 7)、查找 [string rangeOfString:@"world"]; [string hasPrefix:@“www”]; [string hasSuffix:@“com”]; 8)、截取 [string substringFromIndex:2]; [string substringToIndex:5]; [string substringWithRange:range]; 9)、跟基本数据类型转换 [NSString stringWithFormat:@"%d",a]; [NSString stringWithFormat:@"%f",b]; [NSString stringWithFormat:@"%c",c]; [strnum1 intValue]; [strnum2 floatValue]; const char *cc = [strchar UTF8String]; 10)、取元素 [newstring characterAtIndex:3] 11)、字符串是否包含 [mString containsString:@"hello"];
1-2、可变字符串:
1)、创建 1-1)、类方法 [NSMutableString stringWithString:string]; [NSMutableString stringWithFormat:@"%@",string]; 1-2)、对象方法 [[NSMutableString alloc]initWithString:string]; [[NSMutableString alloc]initWithFormat:@"%@",string]; 2)、替换 [mString replaceCharactersInRange:NSMakeRange(2,2) withString:@"xxx"]; 3)、插入 [mString insertString:@"aaa" atIndex:1]; 4)、删除 [mString deleteCharactersInRange:NSMakeRange(1, 3)]; 5)、追加 [S_1 appendString:@"QAZ"]; [S_1 appendFormat:@"%@",S_1];
2-1、数组:
1、创建
1-1)、
NSArray *array1 = [[NSArray alloc]init];
array1 = @[@"here",@"is",@"China"];
1-2)、类方法
NSArray *array2 = [NSArray arrayWithObject:@"hello"];
NSArray *array3 = [NSArray arrayWithObjects:@"here",@"is",@"china", nil];
NSArray *array4 = [NSArray arrayWithArray:array1];
1-3)、对象方法
NSArray *array5 = [[NSArray alloc]initWithObjects:array1,array5, nil];
NSArray *array6 = [[NSArray alloc]initWithObjects:@"here",@"is",@"china", nil];
NSArray *array7 = [[NSArray alloc]initWithArray:array1];
2)、取下标元素
array5[2];
[array5 objectAtIndex:2];
3)、长度
array5.count
[array5 count]
4)、是否包含某个元素
[array7 containsObject:@"hello”];
5)、通过元素获取下标
[array10 indexOfObject:@"1123”];
6)、数组连接成字符串,字符串分割成数组
NSString *string = [array1 componentsJoinedByString:@","];
NSArray *array2 = [string componentsSeparatedByString:@","];
7)、访问第一个、最后一个元素
[array1 firstObject];
[array1 lastObject];
8)、数组遍历
for (NSString *str in array1)
{
NSLog(@"->%@",str);
}
9)、追加元素,生成新的数组
NSArray *array8 = [array1 arrayByAddingObject:@"hello"];
NSArray *array9 = [array1 arrayByAddingObject:array3];
NSArray *array10 = [array1 arrayByAddingObjectsFromArray:array3];
2-2、可变数组:
1、创建
NSMutableArray *mArray = [[NSMutableArray alloc]initWithObjects:@"hello",@"world",@"china", nil];
2、添加元素
2-1)、
[mArray addObject:@"American"];
2-2)、
NSArray *array = [[NSArray alloc]initWithObjects:@"hi",@"hei", nil];
[mArray addObjectsFromArray:array];
3、删除元素
[mArray removeAllObjects];
[mArray removeObject:@"here"];
[mArray removeObjectAtIndex:3];
[mArray removeLastObject];
[mArray removeObjectsInArray:arraytest];
[mArray removeObjectsAtIndexes:set1];
[mArray removeObject:@"here" inRange:NSMakeRange(0, 3)];
[mArray removeObjectsInRange:NSMakeRange(1, 4)];
4、交换位置
[mArray exchangeObjectAtIndex:0 withObjectAtIndex:3];
5、替换
[mArray replaceObjectAtIndex:0 withObject:@"objxxx"];
6、插入
[mArray3 insertObject:@"iiiii" atIndex:1];
7、遍历
int i=0;
for (NSString *str in mArray)
{
NSLog(@"%@",str);
NSLog(@"%d",i++);
}
3-1、字典:
1)、创建
1-1)、
NSDictionary *dic = [[NSDictionary alloc]init];
dic = @{
@"name":@"xiaoming",
@"age":@"18",
@"sex":@"男",
};
1-2)、类方法
NSDictionary *dic1 = [NSDictionary dictionaryWithDictionary:dic];
1-3)、对象方法
NSDictionary *dic2 = [[NSDictionary alloc]initWithObjectsAndKeys:@"xiaohong",@"name",@"20",@"age",@"男",@"sex", nil];
NSDictionary *dic3 = [[NSDictionary alloc]initWithDictionary:dic2];
2)、长度
dic2.count
[dic2 dic2];
3)、根据key获取value
[dic objectForKey:@"age"]
dic[@"age"]
4)、取出所有的key
NSArray *keyArray = [dic allKeys];
5)、取出所有的value
NSArray *valueArray = [dic allValues];
3-2、可变字典:
1、创建
1-1)、
NSMutableDictionary *mDic1 = [NSMutableDictionary dictionary];
1-2)、对象方法
NSMutableDictionary *mDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"xiaoming",@"name",@"19",@"age",@"男",@"sex", nil];
2)、添加元素
[mDic setObject:@"80kg" forKey:@"weight"];
3)、删除元素
[mDic removeObjectForKey:@"age"];
[mDic removeObjectsForKeys:array];
[mDic removeAllObjects];
4)、遍历
for (NSString *key in mDic)
{
NSLog(@"%@",mDic[key]);
}
4、集合
1)、初始化 1-1)、 NSSet *set = [[NSSet alloc]initWithObjects:@"1",@"2",@"3",@"4",@"3", nil]; 1-2)、可变集合初始化 NSMutableSet *mSet = [NSMutableSet set]; 2)、可变添加对象 [mSet addObject:numobject]; 3)、个数 newSet.count [newSet count] 4)、任意取! 但不保证随机! [set anyObject] 5)、是否元素全相同 [set isEqualToSet:newSet] 6)、是否包含 [newSet isSubsetOfSet:set] 7)、消除数组相同元素 7-1)、建个数组 NSArray *array = [NSArray arrayWithObjects:@"3",@"4",@"3", nil]; 7-2)、取数组的对象初始化 NSSet *newSet = [NSSet setWithArray:array]; 7-3)、又把set的对象给数组,自动消除重复 NSArray *newArray = [newSet allObjects];
5、枚举
1)、将 集合set 的值给枚举
NSEnumerator *enumtor = [set objectEnumerator];
2)、将枚举里的对象一一打印
for (NSObject* obj in enumtor)
{
NSLog(@"-->%@",obj);
}
浙公网安备 33010602011771号