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
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.
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.
sizeof is receiving the size of the pointer. Instead use int arraysize = [dirContents count];
Taking sizeof
is not the right way of finding the number of NSArray
elements. Use dirContents.count
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.