简体   繁体   English

使用分配会减少使用的内存量吗?

[英]Does Using Assign reduce the amount of memory used?

When I use assign when declaring a synthesized propery, does ARC automatically still create a matching ivar to it? 当我在声明综合属性时使用assign时,ARC是否仍会自动为其创建匹配的ivar? My property is as follows 我的财产如下

@property (nonatomic, assign) NSString *text:

And

- (NSString *)text {
    return self.label.text; // label is a UILabel
}

- (void)setText:(NSString *)text {
    self.label.text = text;
}

I never have any use for the automatically generated _text ivar; 我从来没有用过自动生成的_text ivar; does the compiler still create this ivar when I omit @synthesize text = _text or does the unused ivar just persist in the memory unused? 我忽略@synthesize text = _text时,编译器是否仍会创建此ivar,还是未使用的ivar持久存在于未使用的内存中?

Do not use assign this way. 不要以这种方式使用assign It probably won't matter in this particular case, but it's extremely confusing to the caller, and it'll generate very bad bugs if you ever change the implementation. 在这种特定情况下,这可能无关紧要,但是这对调用者来说非常令人困惑,如果您更改实现,它会生成非常糟糕的错误。

The fact that you implemented the getter and setter means that the compiler won't generate an ivar. 实现getter和setter的事实意味着编译器不会生成ivar。 That has nothing to do with what memory-management attribute you use. 这与您使用的内存管理属性无关。 Use strong here because that's what you implemented. 在这里使用strong ,因为这就是您实现的。 Your header should match your implementation. 您的标头应与您的实现相匹配。

The ivar is created automatically for you only if you haven't implemented your property yourself. 仅当您尚未实现属性时,才会自动为您创建ivar。 And the @synthesize text = _text; @synthesize text = _text; is done automatically unless you provide your own implementation for getter and setter or synthesize the property to some other variable. 除非您提供自己的getter和setter实现或将属性合成为其他变量,否则此操作将自动完成。 For example: 例如:

@synthesize text;

The above will synthesize text property to text variable. 上面将合成text属性为text变量。

As for using assign instead of copy, that will theoretically use less memory, but is dangerous at the same time. 至于使用assign而不是copy,理论上将使用较少的内存,但同时很危险。 If you use mutable strings, if you change the string value after assigning it to a property, the property value will also change, which is not what you want in most cases. 如果使用可变字符串,则在将字符串值分配给属性后更改该字符串值时,该属性值也会更改,这在大多数情况下不是您想要的。

Are you worried about 4-8(32/64 bit pointers) bytes of extra allocations per instance? 您是否担心每个实例有4-8(32/64位指针)个字节的额外分配? Using assign, weak or strong strong will not change the memory footprint. 使用assign,weak或strong强势将不会更改内存占用量。 No matter what you use the string is not copied the reference always points to the same instance. 无论您使用什么字符串都不会被复制,引用总是指向相同的实例。 The difference is only that the assig, weak do not increase the ref count of the object so by omitting the ivar you only "save" 4-8 bytes depending on what architecture you use. 区别只是assig,weak不会增加对象的引用计数,因此通过省略ivar,您仅可以“保存” 4-8字节,具体取决于所使用的体系结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM