Question

It's common knowledge that we should use the attribute (assign) on primitive properties in Objective-C, yet I've never had a clear explanation as to why we do this.

consider

[myObject setIntProperty:22];

for class myObject that has a @property (nonatomic, assign) int intProperty;

My imagination says we would be assigning intProperty a pointer to stack memory that holds the value 22. So since that pointer has to live on for our property to have any value, does this mean that every primitive has an unlimited lifetime in stack memory?

Some more code to illustrate what I don't understand:

MyObject.h ----

@interface MyObject : NSObject
@property (nonatomic, assign) int myInt;
@property (nonatomic, assign) NSString* myString;
@end

OtherFile.m ----

-(void) doSomething
{
   int x = 22;
   NSString* str = @"something";

   MyObject* obj = [[MyObject alloc] init];

   obj.myInt = x;
   obj.myString = str;

   [self doSomethingInOtherFunctionWith:obj];
}

Now once the doSomething function has completed and moved on, the assigned string myString now points to nothing, since it shared a pointer with the function's local str, which is destroyed after the function runs. But myInt remains as 22.

I understand that this is the way it works, being passed by value, and I do not question HOW it works, just WHY. Doesn't an int have to be a pointer at some level?

Was it helpful?

Solution

Why do we always assign Objective-C primitives?

Because we can't retain or copy them - that's for Objective-C objects only.

My imagination says we would be assigning intProperty a pointer to stack memory

No, not really. We are assigning an int to it. Of course, internally, the instance variable is implemented as a pointer-to-int into the myObject object, with some offset added (described by the instance variable layout of the class).

But if by "stack variable", you mean "objects [that's the C terminology for variables] with automatic storage duration", then no. Objective-C objects are usually allocated dynamically (maybe "on the heap", but that's really irrelevant), and live as long as they are not deallocated, i. e. until their reference count reaches zero. Then they are deallocated, destroyed, and all of their instance variables (which back the corresponding @propertyes) are invalidated as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top