简体   繁体   中英

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? 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; does the compiler still create this ivar when I omit @synthesize text = _text or does the unused ivar just persist in the memory unused?

Do not use assign this way. 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. That has nothing to do with what memory-management attribute you use. Use strong here because that's what you implemented. Your header should match your implementation.

The ivar is created automatically for you only if you haven't implemented your property yourself. And the @synthesize text = _text; is done automatically unless you provide your own implementation for getter and setter or synthesize the property to some other variable. For example:

@synthesize text;

The above will synthesize text property to text variable.

As for using assign instead of copy, that will theoretically use less memory, but is dangerous at the same time. 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? Using assign, weak or strong strong will not change the memory footprint. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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