6

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.

4 Answers 4

21

Use NSArray

NSArray *stringArray = [NSArray arrayWithObjects:@"1", @"2", nil];
NSLog(@"count = %d", [stringArray count]);
Sign up to request clarification or add additional context in comments.

9 Comments

Yes i will be using a mutable array in the end. But just out of curiosity. Is there really no way you can retrieve this length?
Actually, you should use [stringArray count] since it's an instance method and not a property.
@Rengers That does not make any difference. A readonly property is exactly the same as an instance method.
@Rengers, count - is a getter. It can be used as a property
I know it doesn't make any difference. It's just that it's a wrong habit to call methods using the property notation ;).
|
5

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.

Comments

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

Comments

0

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 ) ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.