Array of Objective-c

I am a little confused as I use 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 "Tom" directive, however, when I infer the size of the array, it says that the array has 8 entries, when there are only 4 files in this directory? This will not be a problem, but since I use a for loop as soon as I get,

 NSString *volume1 = [dirContents objectAtIndex:4]; 

(4 - value in the for loop), the application crashes and refuses to start?

Thanks for any help

+4
source share
4 answers

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

sizeof is a c-style statement that will not work correctly with Objective-C objects.

+3
source

sizeof does not return the length of the array, but the size of your variable is in memory. Since dirContents is a pointer, it takes only 8 bytes.

To get the length of the array, you should use

 [dirContents count]; 

In addition, objects are stored in arrays with indices starting from 0. Thus, if your array has only 4 elements, [dirContents objectAtIndex:4] will fail at runtime, since you are trying to get the element in fifth position.

+2
source

sizeof gets the size of the pointer. Use int arraysize = [dirContents count];

+2
source

Taking sizeof not the right way to find the number of NSArray elements. Use dirContents.count .

+2
source

Source: https://habr.com/ru/post/1388835/


All Articles