views:

53

answers:

2

Hey guys,

I have sort of a simple question. I am writing an Objective-C program with some multithreading. I have a global NSArray, and I add objects into that NSArray from a method that is called in a new thread. If the objects I add into that NSArray are new objects created in that method (local), will that create memory access and/or other issues or will the garbage collector be smart enough to keep those objects around until they have no more references? Also, if I want to an object into that NSArray, will that object be passed by reference or by value?

Thanks, Hassaan

A: 

There should be no problems with the design you're describing. All of your threads share the same memory space, so everything will work just fine. The memory management system will do "the right thing", but I recommend learning the retain/release method - there's nothing better than actually understanding what your program is doing.

Objective-C is pass-by-value only, just like C. That said, objects are only ever passed around by pointers in Objective-C, so you can think of it as always pass-by-reference in that sense.

Carl Norum
Thanks! I just updated my post with another question. Would you please take a look at that one as well?
hassaanm
@hassaanm, edited. Watch out for potential threading problems as @taskinoor mentions in his answer.
Carl Norum
This should not be downvoted. It also contains useful information and nothing is technically wrong.
taskinoor
A: 
  1. Can you add objects in NSArray? I guess you mean NSMutableArray.
  2. NSMutableArray is NOT thread safe. So you may need to acquire a lock before trying to modify it. Though this will mostly dependent on how your threads are working on shared data.
  3. NSArray or NSMutableArray will retain the objects that they contains. So after adding you can release the local copy.
  4. The array will store the reference.

Hope it helps. In general multithreading is much more difficult than a single thread app. Please check Threading Programming Guide for the details. It may save you from many hazards.

taskinoor
Yes, I meant NSMutableArray.
hassaanm
THANKS FOR THE HELP!
hassaanm