objective-c - 在 Objective-C Cocoa 框架中将日期信息放入数组中

标签 objective-c cocoa

我有一个函数,它返回一个数组来保存日期信息。

- (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;
}
  • 问题1:有没有一种简单的方法可以获取数组中的所有信息(年、月、日、时、分...),而无需一遍又一遍地使用setDateFormat
  • Q2:有没有办法让我可以使用 res['year'] 或类似的方法访问数组的内容?我的意思是使用字典?
  • Q3:我需要在此函数的调用方中释放 NSArray *res 吗?

最佳答案

A1:你可以这样做:

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

A2:使用 NSDictionary:

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

A3:返回值自动释放。您不需要释放它。

关于objective-c - 在 Objective-C Cocoa 框架中将日期信息放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5138112/

相关文章:

iphone - 模拟一个水龙头,可以吗?

objective-c - 在 OSX 中编写 IDE 或文本编辑器

ios - ipad 从左到右的半展示

iphone内存管理奇怪的问题

Objective-C:什么是惰性类?

objective-c - NSKeyedArchiver .plist 附加问题

ios - 从我的 Parse 数据库中获取任意数量的 UserID 的最快方法

objective-c - 如何在 Xcode (Cocoa) 中检索文件的图标

objective-c - IKImageBrowserView 中重新排序的数据源方法,未被调用

swift - 在没有 nib 的情况下使用 NSTableView 创建 NSScrollView——缺少对 TableView 的约束