I am new to Objective C. I have a small doubt on memory allocation.
If we declare & allocate memory for a NSArray like this:
NSArray * arr = [[NSArray alloc]init];
how much memory will be allocated for the array arr?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Hmm. If you really meant
NSArray, then the array will be empty, no elements will be stored in it, hence only a small amount of memory is needed that would be needed for any Objective C object anyway. (The exact amount of memory is an implementation detail). But an emptyNSArraythat cannot be modified is not of much use, so I guess you meantNSMutableArray. ForNSMutableArray, the array will be empty initially, but it may still allocate some extra memory (and it is very likely that it will) because Objective C expects the array to grow and it’s easier to add new elements to the array if there is already some memory allocated on top of what is strictly needed. The exact amount of extra memory allocated is also an implementation detail.If you want to ensure that your array takes up as little memory as possible, you can use
[[NSMutableArray alloc] initWithCapacity:x]wherexis the maximum number of elements you intend to put in the array. It will still have zero size but Objective C will assume that you are going to addxelements to it sooner or later hence it allocates a backing store that is enough forxobjects.