在oc 中,如果对象没有被强引用,会被立即释放。
__weak 表示弱引用 :
Assigning retained object to weak variable; object will be released after assignment
控件的使用 :
[self.view addSubview:_noLabel];
//将弱引用参照的_noLabel添加到视图UIView;
UIViewController.h-》@property(null_resettable, nonatomic,strong) UIView *view;
-》UIView.h :@property(nonatomic,readonly,copy) NSArray<__kindof UIView *> *subviews;
-》强引用UILabel对象,所以这个UILabel对象已经有拥有者,不会被放--再添加过程都是操作UILabel对象的地址
释放对象的过程:
因为这些对象不会有UIViewController的控制,来进行强引用。
即使你声明一个NSString的属性,有人可能传入一个NSMutableString的实例,然后在你没有注意的情况下修改它。
当一个对象不再有strong类型的指针指向它的时候 它会被释放 ,即使还有weak型指针指向它。
一旦最后一个strong型指针离去 ,这个对象将被释放,所有剩余的weak型指针都将被清除。
例子:
有缓存方式的加载方法
无缓存方式将图片加载至内存
常见的优化点有: 数据独立性的处理(plist、网络)、魔法数字的问题解决(宏,枚举enum)、属性的懒加载(重写getter方法)
代码示例
/** 序列帧动画:顺序播放一组图片 1.提示、如果放置于Assets.xcassets目录中的图片不能使用imageWithContentsOfFile:path进行加载,只能使用imageName进行加载,即内存由系统负责了;Assets.xcassets 存放一些经常使用的小图片素材 2。Supporting Files 目录通常存放,大、不经常使用的图片; */ - (void) frameAnimation : (UIButton *) button{ //如果正在动画播放直接退出,来保证保证一个动画播放完成 if ([self.imageList isAnimating]) {//考虑用户的重复点击进行频繁的展示帧动画问题 return; } //顺序的改变UIImageView 的image,此时需要的参数有:需要播放的序列帧图片数组animationImages(UIImage对象)、帧动画的持续时间animationDuration、帧动画的执行次数animationRepeatCount--可自行查看UIImageView的属性和方法 //动画图片的数组--可修改的数组NSMutableArray(manage a modifiable array of objects) NSMutableArray *arrayImage = [NSMutableArray array];//Creates and returns an empty array. //添加帧动画播放的图片 //设置图片的数组的 for (int i = 0; i< self.animationImages[button.tag].count ; i++) { //获取图片名称 NSString *pictureNamePrefix = self.animationImages[button.tag][i];//获取文件名+扩展名 //方式一:有缓存加载图片 // 添加Image的对象到帧图片数组 // [arrayImage addObject: [UIImage imageNamed:pictureNamePrefix]];//参数为图片名称,png 格式的可以不加扩展名 //方式二:无缓存方式加载图片-指定扩展名 // NSArray *arrayPicture = [pictureNamePrefix componentsSeparatedByString:@"."];//从字符中分隔成2个元素的数组(图片名+扩展名) // NSString *path = [[NSBundle mainBundle] pathForResource:arrayPicture[0] ofType: arrayPicture[1]];//获取图片的全路径 //方式二:无缓存方式加载图片-不指定扩展名 NSString *path = [[NSBundle mainBundle] pathForResource:pictureNamePrefix ofType:nil]; [arrayImage addObject:[ UIImage imageWithContentsOfFile:path]]; } [self.imageList setAnimationImages:arrayImage]; //设置帧动画的持续时间 [self.imageList setAnimationDuration: self.imageList.animationImages.count * 0.1]; //设置帧动画的执行次数 [self.imageList setAnimationRepeatCount:1]; //开始动画 [self.imageList startAnimating]; //释放资源:动画结束之后清除帧动画数组 //nvokes a method of the receiver on the current thread using the default mode after a delay. // [self performSelector:@selector(cleanUpAnimationsArray) withObject:nil afterDelay:self.imageList.animationDuration];//定义在NSObject的分类中@interface NSObject (NSDelayedPerforming) //清除内存的代码简化--可以避免定义cleanUpAnimationsArray方法 [self.imageList performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:self.imageList.animationDuration]; }
iOS解决压缩之后图片模糊的问题