如何通过for语句或枚举打印NSArray对象?

发布于 2024-12-19 16:59:43 字数 341 浏览 2 评论 0原文

可能的重复:
如何迭代 NSArray?

这是我的代码(用于示例):

NSArray *myArray = [NSArray arrayWithObjects:@"Red", @"Blue", @"Green", nil];

我想循环遍历数组,将每个字符串打印到控制台。

谢谢。

Possible Duplicate:
How do I iterate over an NSArray?

Here is my code (for example):

NSArray *myArray = [NSArray arrayWithObjects:@"Red", @"Blue", @"Green", nil];

I want loop through the array printing each string to the console.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暖伴 2024-12-26 16:59:43

最简单的方法就是:

NSLog(@"%@", myArray);

或者,如果您想使用快速枚举以您自己的方式打印每个对象:

for (NSString *string in myArray) {
    NSLog(@"%@", string);
}

The easiest way is just:

NSLog(@"%@", myArray);

Or, if you want to use fast enumeration to print each object in your own way:

for (NSString *string in myArray) {
    NSLog(@"%@", string);
}
烟─花易冷 2024-12-26 16:59:43

让我们找到最复杂的方法,好吗?

NSArray *myArray = [NSArray array];
id *objects = malloc(sizeof(id) * myArray.count);
[myArray getObjects:objects range:NSMakeRange(0, myArray.count)];

char **strings = malloc(sizeof(char *) * myArray.count);

for (int i = 0; i < myArray.count; i++)
{
     strings[i] = [objects[i] UTF8String];
}

printf("<");
for (int i = 0; i < myArray.count; i++)
{
     printf("%s" strings[i]);
     if (i != myArray.count - 1)
         printf(", ");
}
printf(">");

free(objects);
free(strings);

当然,你总是可以这样做:

NSLog(@"%@", myArray);

Let's find the most complex way, shall we?

NSArray *myArray = [NSArray array];
id *objects = malloc(sizeof(id) * myArray.count);
[myArray getObjects:objects range:NSMakeRange(0, myArray.count)];

char **strings = malloc(sizeof(char *) * myArray.count);

for (int i = 0; i < myArray.count; i++)
{
     strings[i] = [objects[i] UTF8String];
}

printf("<");
for (int i = 0; i < myArray.count; i++)
{
     printf("%s" strings[i]);
     if (i != myArray.count - 1)
         printf(", ");
}
printf(">");

free(objects);
free(strings);

Of course, you can always just do it like this:

NSLog(@"%@", myArray);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文