如何在NSArray中NSLog一个对象的名称

时间:2014-06-20 02:05:00

标签: objective-c

我是Objective-C的新手,我目前正在阅读 Objective-C:The Big Nerd Ranch编程指南。我试图在完成的示例中添加一些代码,希望学习如何在数组中打印对象的名称及其值。我能够打印值,但我仍然试图打印对象的名称。任何帮助将不胜感激!

#import <Foundation/Foundation.h>

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

    @autoreleasepool {

        // create three NSDate objects
        NSDate *now = [NSDate date];
        NSDate *tomorrow = [now dateByAddingTimeInterval:24.0 * 60.0 * 60.0];
        NSDate *yesterday = [now dateByAddingTimeInterval:-24.0 * 60.0 * 60.0];

        // create an empty mutable array
        NSMutableArray *dateList = [[NSMutableArray alloc] init];

        // add two dates to the array
        [dateList addObject:now];
        [dateList addObject:tomorrow];

        // add yesterday at the beginning of the list
        [dateList insertObject:yesterday atIndex:0];

        // iterate over the array
        for (NSDate *d in dateList) {
             NSLog(@"Here is the date: %@\n\n", d);
             sleep(2);
        }

        // remove yesterday
        [dateList removeObjectAtIndex:0];
        NSLog(@"Now the first date is: %@\n\n", dateList[0]);

    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

听起来你想使用NSMutableDictionary而不是NSMutableArray,它可以让你为每个对象添加一个对象和一个键。然后,一旦有了Dictionary,就可以使用此循环打印键和值

        for (NSString *key in dict) {
            NSLog(@"'%@' = '%@'", key, [dict objectForKey:key]); 
           }

答案 1 :(得分:0)

你的代码对于理解实际目标是什么有点理论,因此在我的答案中有一些加倍的东西,比如将对象按顺序放入数组中,只是为了再次将它们拉出来,但这是你特别要求的。我想:

NSMutableArray *arrayOf3Days = [NSMutableArray array];
NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTimeInterval:24.0 * 60.0 * 60.0];
NSDate *yesterday = [now dateByAddingTimeInterval:-24.0 * 60.0 * 60.0];


[arrayOf3Days addObject:yesterday];
[arrayOf3Days addObject:now];
[arrayOf3Days addObject:tomorrow];

for (int i = 0; i < arrayOf3Days.count; i++) {

    NSDate *thisDay = [arrayOf3Days objectAtIndex:i];

    if (i == 0) {
        NSLog(@"Yesterday: %@\n\n", thisDay);
    }else if(i == 1){
        NSLog(@"Today: %@\n\n", thisDay);
    }else if(i == 2){
        NSLog(@"Tomorrow: %@\n\n", thisDay);
    }
}