开发者

property assignment followed by autorelease

开发者 https://www.devze.com 2023-03-21 17:17 出处:网络
I have am constantly thinking of making my code less buggy. I\'ve seen this many times when cleaning up other programmers code and am wondering if I\'m right in my assumption that the call in a multit

I have am constantly thinking of making my code less buggy. I've seen this many times when cleaning up other programmers code and am wondering if I'm right in my assumption that the call in a multithreaded environment is not safe:

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

My thinking is that if before the application is done with the function another thread intervenes and releases the prop1 then upon the next runLoop the pointer that was init'd will potentially get released again if prop1 was not set to nil by the other thread.

Timeline开发者_如何学C:

*-----------------**-----------*
|                  |           |
|                  |           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 relieve my concern.


I don't think you have to worry about thread safety any more than you usually would. Having multiple threads writing to the same property is a bad thing and should be avoided (e.g. with locks).

You could get rid of the autorelease using

prop1 = [[SomeClass alloc] init];

instead, i.e. not using the property. I never use autorelease unless it's necessary and in this case it isn't.


It depends on your property type. If you set prop1 as Retain/Copy then 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 set 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 should relase the prop1 e.g.

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

If you want to play safe with multi thread, you can choose one of following:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号