Reputation: 3180
Is there any quick way I can get the number of strings within a NSString array?
NSString *s[2]={@"1", @"2"}
I want to retrieve the length of 2 from this. I there something like (s.size) I know there is the -length method but that is for a string not a string array. I am new to Xcode please be gentle.
Upvotes: 6
Views: 29768
Reputation: 174
Tried to search for _countf in objective-c but it seems not existing, so assuming that sizeof and typeof operators works properly and you pass valid c array, then the following may work.
#define _countof( _obj_ ) ( sizeof(_obj_) / (sizeof( typeof( _obj_[0] ))) )
NSString *s[2]={@"1", @"2"} ;
NSInteger iCount = _countof( s ) ;
Upvotes: 0
Reputation: 130102
Yes, there is a way. Note that this works only if the array is not created dynamically using malloc
.
NSString *array[2] = {@"1", @"2"}
//size of the memory needed for the array divided by the size of one element.
NSUInteger numElements = (NSUInteger) (sizeof(array) / sizeof(NSString*));
This type of array is typical for C, and since Obj-C is C's superset, it's legal to use it. You only have to be extra cautious.
Upvotes: 5