Xcode: counting elements in an array of strings

Is there any quick way to get the number of rows in an NSString array?

NSString *s[2]={@"1", @"2"} 

I want to get a length of 2 . I am there something like (s.size). I know that the -length method exists, but for a string it is not a string array. I'm new to Xcode, be careful.

+6
source share
4 answers

Use NSArray

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

Yes, there is a way. Note that this only works 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 of C, and since Obj-C is a superset of C, it is legal to use. You have to be careful.

+4
source
 sizeof(s)/sizeof([NSString string]); 
+1
source

I tried searching for _countf in objective-c, but it does not seem to exist, therefore, assuming the sizeof and typeof operators are working correctly, and you are passing a valid c array, then the following might work.

 #define _countof( _obj_ ) ( sizeof(_obj_) / (sizeof( typeof( _obj_[0] ))) ) NSString *s[2]={@"1", @"2"} ; NSInteger iCount = _countof( s ) ; 
0
source

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


All Articles