Xcode:计算字符串数组中的元素

Vla*_*col 6 xcode objective-c

有没有快速的方法可以获得NSString数组中的字符串数量?

NSString *s[2]={@"1", @"2"}
Run Code Online (Sandbox Code Playgroud)

我想从中检索2的长度.我有类似的东西(s.size)我知道有-length方法但是对于字符串而言不是字符串数组.我是Xcode的新手请温柔.

ber*_*ium 20

使用NSArray

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

  • 实际上,你应该使用`[stringArray count]`,因为它是一个实例方法而不是属性. (2认同)

Sul*_*han 5

是的,有办法。请注意,这仅在未使用 动态创建数组时才有效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*));

Run Code Online (Sandbox Code Playgroud)

这种类型的数组是 C 的典型,因为 Obj-C 是 C 的超集,所以使用它是合法的。你只需要格外小心。