【iOS】关于视图生命周期、NSString变CGPath等问题

来源:互联网 发布:淘宝大学开网店视频 编辑:程序博客网 时间:2024/05/21 17:25

这几天遇到的问题集中解决一下。

1.首先是视图生命周期,这个博客写的很清楚。点击打开链接

如果有个TestViewController,那么

TestViewController *testVC = [[TestViewController alloc] init];

只会分配内存并初始化这个视图控制器,并不会去加载它的视图。系统在需要显示testVC的视图时会自动调用loadView去加载,官方推荐永远不要手动调用loadView,这样符合“Lazy Loading”的原则。

如果在TestViewController的init方法里写了

[self.view setBackgroundColor:[UIColor redColor]];

类似,只要出现了self.view,系统就会去加载view。而如果此时并不需要用(显示)这个view,就造成了内存浪费。更严重的,如果内存不足,系统会检测到testVC并没有显示,而其view在内存中,那么释放其view并且再次用到时只会loadView不会init,这样背景色设置就不会起作用了(用iOS7模拟器没模拟成功)

目前的理解是:init中尽量少进行一些操作除非必须,然后在viewDidLoad或者viewWillAppear中构建视图的各个控件。

2.NSString变CGPath

这个在SOF上有个问题Why does my NSString becomes CGPath?

答案一给出的回答:

Effects like this typically happen when you store a pointer to an object that was released and deallocated. 
基本就是空指针赋值问题,完了还读了一下,就出错了。

If you want to ensure that your NSString stays alive, you need to take ownership of it. You can do that by either 
retaining it or copying it.
那么可以通过retain或copy保证NSString对于赋给它值的字符串对象保留所有权(一般NSString的话可以用copy),如下:

teststring = [[args objectAtIndex:0] copy];


答案二给出的回答:

用property和synthesize,要注意在非allo init的地方,都要用self.testString来访问,这样会通过setter方法进而给property设置的retain啊copy啊参数才会起作用

值得注意的是,dealloc中,以前看到有人写:

[_nickName release],_nickName=nil;
实际上如果用synthesize生成的setter,这样:

self.teststring = nil;
调用setter会自动release旧值。上面的例子是直接处理实例变量,只有property没有synthesize所以用下划线访问(但是也有setter和getter)。

The setter method also releases any old value in the property before assigning a new value, so setting it to nil 
releases the old value.



0 0
原创粉丝点击