将日期信息放入Objective-C可可框架中的数组 [英] Getting date info into an array in Objective-C Cocoa framework

查看:53
本文介绍了将日期信息放入Objective-C可可框架中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回数组以保存日期信息的函数.

I have a function that returns an array to hold date info.

- (NSArray*) getTodayArray
{


    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"YYYY"];
    NSString *year = [dateFormatter stringFromDate:today];

    [dateFormatter setDateFormat:@"MM"];
    NSString *month = [dateFormatter stringFromDate:today];

    [dateFormatter release]; 

    NSArray *res = [NSArray arrayWithObjects: year, month, nil];

    return res;
}

  • Q1:是否有一种简便的方法可以一次又一次不使用 setDateFormat 来获取数组中的所有信息(年,月,日,时,分...)?
  • Q2:是否可以使用 res ['year'] 或类似的方法访问数组的内容?我的意思是使用字典?
  • Q3:我需要在此函数的调用方中释放 NSArray * res 吗?
    • Q1 : Is there any easy way to get all the info (year, month, date, hour, minute ...) in an array not using setDateFormat over and over again?
    • Q2 : Is there a way so that I can access the content of array using res['year'] or similar? I mean using dictionary?
    • Q3 : Do I need to release NSArray *res in the caller of this function?
    • 推荐答案

      A1:您可以这样做:

      A1: You can do smth like this:

          NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
          [dateFormatter setDateFormat:@"YYYY|MM"];
          NSArray* d_arr = [[dateFormatter stringFromDate: [NSDate date]] componentsSeparatedByString: @"|"];
      

      A2:使用NSDictionary:

      A2: Use NSDictionary:

      [NSDictionary dictionaryWithObjectsAndKeys: [d_arr objectAtIndex: 0], @"year", [d_arr objectAtIndex: 1], @"month", nil]
      

      A3:返回值是自动释放的.您不需要释放它.

      A3: return value is autoreleased. you don't need to release it.

      这篇关于将日期信息放入Objective-C可可框架中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆