Vlad Otrocol
Vlad Otrocol

Reputation: 3180

Xcode : Count elements in string array

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

Answers (4)

redwud
redwud

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

Sulthan
Sulthan

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

Rengers
Rengers

Reputation: 15228

sizeof(s)/sizeof([NSString string]);

Upvotes: 1

beryllium
beryllium

Reputation: 29767

Use NSArray

NSArray *stringArray = [NSArray arrayWithObjects:@"1", @"2", nil];
NSLog(@"count = %d", [stringArray count]);

Upvotes: 21

Related Questions