New to Objective C: Need help understanding strong reference vs assign

隐身守侯 提交于 2019-12-11 11:09:14

问题


first post. Sorry if I screwed up the code rules. I'm trying to learn Objective C from the Big Nerd Ranch Guide. I'll post the example dealing with strong references.

#import <Foundation/Foundation.h>

@interface Asset : NSObject
{
  NSSTRING *label;
  unsigned int resaleValue;
}
@property (strong) NSString *label;
@property unsigned int resaleValue;
@end

So basically the NSString needs a strong reference whereas the int does not. I'm aware that NSString is an object, and I've read that if nothing is specified a variable is given the property of assign.

So if assign is good enough to keep something like an int from being freed until the object owning it is freed, how come it's not good enough to keep the NSString object within the Asset object from being freed? Ultimately I guess I'm still confused about what assign does in terms of reference counting vs. what strong does (or perhaps I should say retain since that is what strong replaced in ARC).


回答1:


strong == to std::shared_ptr if you come from C++

strong states that the object must be retained and released respectively during assignment.

-(void)assign:(id) b to:(id) a {
    if( b ){
      [b retain];
    }
    if ( a ){
      [a release];
    }
    a = b;

}

To answer your second question, the size of an objective-C object is not defined like a structure. Thus obj-C classes can not be held by value.

Thus all data inside of an obj-c class compiled as obj-c will always have plain old data types stored within it since their size can be determined as fixed.

Consider a buffer of 8 bytes;

The first 4 bytes are for your int the second 4 bytes are your pointer, since having a variable length string would change the size of the object at run time you see how this wouldn't work, a string is allocated on the heap and assigned to your pointer.



来源:https://stackoverflow.com/questions/10292031/new-to-objective-c-need-help-understanding-strong-reference-vs-assign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!