Assignment of real estate, followed by abstract

I am constantly thinking about making my code less buggy. I have seen this many times when cleaning up the code of other programmers, and I wonder how right I am in my assumption that a call in a multi-threaded environment is unsafe:

self.prop1 = [[[SomeClass alloc] init] autorelease]; 

I think that if before the application is executed using the function, another thread intervenes and frees prop1, and then on the next runLoop a pointer that was init'd will potentially be released again if prop1 was not set to zero by another thread .

 Timeline: *-----------------**-----------* | | | | | Thread 1 autoreleases prop1 when done with function | | | Thread 2 releases prop1 | Thread 1 calls the above code and doesn't finish the function 

I hope this makes sense to someone, and they can clarify or ease my concern.

+4
source share
2 answers

It depends on your type of property. If you set prop1 as Retain / Copy, you should write like this:

 @property (nonatomic, retain) id prop1; if(self.prop1 == nil) { SomeClass *obj = [[SomeClass alloc] init]; self.prop1 = obj; [obj release]; } 

if you install prop1 as Assign then

 @property (nonatomic, assign) id prop1; if(self.prop1 == nil) { SomeClass *obj = [[SomeClass alloc] init]; self.prop1 = [obj retain]; [obj release]; } 

In dealloc you must pass prop1, for example.

 - (void)dealloc { [prop1 release]; [super dealloc]; } 

If you want to play in safe mode with multiple streams, you can choose one of the following options:

 1. Make property atomic 2. Use @synchronized over prop1 3. Use Mutex Lock 
0
source

I don’t think you need to worry about thread safety more than usual. Having multiple threads writing the same property is bad and should be avoided (for example, with locks).

You can get rid of auto advertising by using

 prop1 = [[SomeClass alloc] init]; 

those. without using a property. I never use autorelease if necessary, in which case it is not.

+1
source

All Articles