【问题标题】:Printout for fast enumeration打印输出用于快速枚举
【发布时间】:2015-03-27 15:28:10
【问题描述】:

哪些代码行允许我们通过快速枚举打印迭代而不重复前言?我的代码如下:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        // Create an empty mutable array
        NSMutableArray *listGroceries = [NSMutableArray array];

        // Add two dates to the array
        [listGroceries addObject:@"Container of milk"];
        [listGroceries addObject:@"Stick of butter"];

        // Add yesterday at the beginning of the list
        [listGroceries insertObject:@"Loaf of bread" atIndex:0];

        // How many dates are in the array?
        NSLog(@"There are %lu Groceries", [listGroceries count]);

        for (NSDate *d in listGroceries) {
            NSLog(@"My grocery list is: %@", d);
        }

    }
    return 0;
}

代码结果如下:

2015-03-26 14:05:42.553 Groceries[3131:129994] My grocery list is: Loaf of bread
2015-03-26 14:05:42.553 Groceries[3131:129994] My grocery list is: Container of milk
2015-03-26 14:05:42.553 Groceries[3131:129994] My grocery list is: Stick of butter

如何让程序生成以下内容,而不会在之后的每一行都重复 My grocery list is

    My grocery list is:
    Loaf of bread
    Container of milk
    Stick of butter

【问题讨论】:

  • 使用 printf() 代替 NSLog,并应用有效逻辑

标签: objective-c fast-enumeration


【解决方案1】:

这是你的答案:

    int main(int argc, char * argv[]) {
    @autoreleasepool {

    // Create an empty mutable array
    NSMutableArray *listGroceries = [NSMutableArray array];

    // Add two dates to the array
    [listGroceries addObject:@"Container of milk"];
    [listGroceries addObject:@"Stick of butter"];

    // Add yesterday at the beginning of the list
    [listGroceries insertObject:@"Loaf of bread" atIndex:0];

    // How many dates are in the array?
    NSLog(@"There are %lu Groceries", [listGroceries count]);

    printf("My grocery list is: \n");

    for (NSString *d in listGroceries) {

        printf("%s \n", d.UTF8String);
    }


    return 0;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多