ios - alloc 和 init 和synthesize 等内存分配的疑惑?
ringa_lee
ringa_lee 2017-04-17 17:31:37
0
3
336

我是一个OC的初学者,有一定的C++基础,学习OC(目前版本)最大的感觉是过于自动化,导致理解有断层。比如,实例变量的隐藏。。让我困惑了许久。。
特别是对于内存这一块,

  • 比如@synthesize 自动生成的getter & setter 是否可以正确的初始化堆上的属性。

  • stringWithFormat 类似方法可以返回一个实例,接受的变量不需要alloc 和 init。

  • NSFont 使用的时候,不可以alloc 和 init。

基于以上疑惑,引出我很低级的发问的。

  1. 所有堆上的属性,都需要在setter 或 getter 进行内存分配(无论是alloc init,或者像stringWithFormat 这样的也可以)

  2. @synthesize 自动生成的getter & setter 是不是仅仅生成 _value = value这段代码。对堆上的属性是不好用的

  3. 对于类使用alloc,alloc 究竟分配了什么内存?属性所占得内存会不会被分配。

ringa_lee
ringa_lee

ringa_lee

reply all(3)
刘奇

I have never used c++, so I may not be able to get your doubts.
1. Memory allocation is never in the setter or getter method, alloc is.
@synthesize tells the compiler to help generate setter and getter methods. The current version uses @synthesize by default, so writing methods like @synthesize value=_value are no longer used. The previous writing was to tell the compiler that when I want to access the value attribute, please access the _value ivar. For details, see here: http://stackoverflow.com/questions/3266467/what-exactly-does-synthesize -do
2.stringWithFormat is a class method. Alloc and init have been called internally. This is similar to the fact that NSFont does not use alloc and init. All externally provided interfaces have already called alloc and init in the method implementation. If If you really want to call it, you can call it. If it doesn't exist, you can't. NSFont *f = [[NSFont alloc] init]; Code like this is no problem.
3.alloc allocates heap memory. Will the memory occupied by the attribute be allocated? I don't quite understand what this sentence means. Since the memory has been occupied, it must have been allocated to it.

洪涛

Now iOS development no longer needs to use @synthesize. When you add a property, the system will automatically add an instance variable with the same name and underline as the property, and automatically generate the setter and getter methods of this instance variable.

stringWithFormat Similar methods can return an instance, and the accepted variables do not require alloc and init.
//There are two types of class methods and instance methods in OC. After the class method is called, an object will be returned, which is equivalent to performing the alloc+init operation

For the concepts of attributes and objects, you can visit my blog (www.hcios.com) and search for: attributes and objects to get detailed answers.

左手右手慢动作

The stringWithFormat and NSfont methods of NSString you call are both class methods. You can take a look at what is an instance method and what is a class method

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!