4

I am slightly confused as I am using this piece of code;

NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/Volumes/" error:nil];

int arraysize = sizeof dirContents;

to get an array of the contents of the "Volumes" direcoty, however when I output the array size it says that the array has 8 entries when there are only 4 files in that directory? This wouldn't be a problem but since I am using a for loop as soon as I get to;

NSString *volume1 = [dirContents objectAtIndex:4];

(4 being the value in the for loop) the application crashes and refuses to launch?

Thanks for any help

1
  • sizeof dirContents tells you that the pointer "dirContents" is eight bytes long. Has absolutely nothing to do with the array itself. Commented Jan 1, 2012 at 20:14

4 Answers 4

3

You should use int arraysize = [dirContents count] to get the correct size.

sizeof is a c-style operator that will not work correctly on Objective-C objects.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that worked but I am curios why does the way I found on the web not work?
because sizeof returns the length of the pointer to the Objective-C object in memory. Just the size of the pointer not the object, and certainly not the size/count of the NSArray.
sizeof will give you the size of NSArray*. sizeof pointer being 8 means you're compiling for 64 bit platform
Ah, I do forget about that :-)
2

sizeof is receiving the size of the pointer. Instead use int arraysize = [dirContents count];

Comments

2

Taking sizeof is not the right way of finding the number of NSArray elements. Use dirContents.count instead.

Comments

2

sizeof does not returns the length of the array but the size your variable occupies in memory. Since dirContents is a pointer it occupies only 8 byte.

To get the length of the array you should use

[dirContents count];

Besides, in arrays, objects are stored with indexes starting from 0. Thus, if your array has only 4 elements, [dirContents objectAtIndex:4] will end in a runtime error, since you are trying to retrieve the element in the fifth position.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.