【问题标题】:Return NSArray from NSDictionary从 NSDictionary 返回 NSArray
【发布时间】:2011-06-26 01:08:30
【问题描述】:

我有一个 fetch,它返回一个数组,其中包含核心数据对象属性的字典。

这是我之前的问题:Create Array From Attribute of NSObject From NSFetchResultsController

这是获取:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:NO]; //set to YES if you only want unique values of the property
[request setPropertiesToFetch :[NSArray arrayWithObject:@"timeStamp"]]; //name(s) of properties you want to fetch

// Execute the fetch.
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];

当我记录 NSArray data 时,我得到了这个:

The content of data is(
        {
        timeStamp = "2011-06-14 21:30:03 +0000";
    },
        {
        timeStamp = "2011-06-16 21:00:18 +0000";
    },
        {
        timeStamp = "2011-06-11 21:00:18 +0000";
    },
        {
        timeStamp = "2011-06-23 19:53:35 +0000";
    },
        {
        timeStamp = "2011-06-21 19:53:35 +0000";
    }
)

我想要的是一个这样格式的数组:

[NSArray arrayWithObjects: @"2011-11-01 00:00:00 +0000", @"2011-12-01 00:00:00 +0000", nil];'

编辑:

这是我想用我的新数据数组替换数据数组的方法:

- (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate {    
    NSLog(@"calendarMonthView marksFromDate toDate");   
    NSLog(@"Make sure to update 'data' variable to pull from CoreData, website, User Defaults, or some other source.");
    // When testing initially you will have to update the dates in this array so they are visible at the
    // time frame you are testing the code.
    NSArray *data = [NSArray arrayWithObjects:
                     @"2011-01-01 00:00:00 +0000", @"2011-12-01 00:00:00 +0000", nil]; 


    // Initialise empty marks array, this will be populated with TRUE/FALSE in order for each day a marker should be placed on.
    NSMutableArray *marks = [NSMutableArray array];

    // Initialise calendar to current type and set the timezone to never have daylight saving
    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    // Construct DateComponents based on startDate so the iterating date can be created.
    // Its massively important to do this assigning via the NSCalendar and NSDateComponents because of daylight saving has been removed 
    // with the timezone that was set above. If you just used "startDate" directly (ie, NSDate *date = startDate;) as the first 
    // iterating date then times would go up and down based on daylight savings.
    NSDateComponents *comp = [cal components:(NSMonthCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit | 
                                                    NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) 
                                          fromDate:startDate];
    NSDate *d = [cal dateFromComponents:comp];

    // Init offset components to increment days in the loop by one each time
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setDay:1];    


    // for each date between start date and end date check if they exist in the data array
    while (YES) {
        // Is the date beyond the last date? If so, exit the loop.
        // NSOrderedDescending = the left value is greater than the right
        if ([d compare:lastDate] == NSOrderedDescending) {
            break;
        }

        // If the date is in the data array, add it to the marks array, else don't
        if ([data containsObject:[d description]]) {
            [marks addObject:[NSNumber numberWithBool:YES]];
        } else {
            [marks addObject:[NSNumber numberWithBool:NO]];
        }

        // Increment day using offset components (ie, 1 day in this instance)
        d = [cal dateByAddingComponents:offsetComponents toDate:d options:0];
    }

    [offsetComponents release];

    return [NSArray arrayWithArray:marks];
}

【问题讨论】:

    标签: iphone objective-c cocoa-touch


    【解决方案1】:

    对从获取请求返回的数组对象调用valueForKey。这将依次在每个对象上调用 valueForKey 并返回一个包含所有结果值的数组。

    NSArray *timestamps = [objects valueForKey:@"timeStamp"];
    

    【讨论】:

    • 太棒了。我喜欢 KVC,并且每天都在学习它的新知识。
    • 谢谢阿努拉格。但由于某种原因,数据仍然没有加载我的日历视图。这是一张显示 2 个数组的图片,底部的一个可以很好地加载数据,并与示例应用程序一起提供。顶部是我的,不加载数据。是因为我的时间戳需要在小时和时间为 000000 吗? box.net/shared/static/s27n3hmab6r11n633pmo.png
    • 实际上,我刚刚发布了上面的方法,该数组将用于该方法。也许我可以改变一些东西,以便时间 0000000 与我的 timeStamps 中的时间没有区别?
    • @RyanR - KVC 为 Cocoa 提供了非常坚实的基础。我喜欢其他一些语言如何使用mapreduce,filter 处理集合。例如,在 Ruby 中,等价物是 timestamps = objects.map { |object| object[:timestamp] }。希望 Cocoa 将这些方法合并到 NSArray 中,也许那些其他语言会采用 KVC。一厢情愿:)
    • @Anurag:到目前为止,除了您刚才演示的内容之外,我最喜欢的是collection operators。在单行代码中对集合执行功能简直是太棒了。
    【解决方案2】:

    快速枚举法:

    NSMutableArray *data = [[NSMutableArray alloc] initWithCapacity:array.count];
    for (NSDictionary *d in objects) {
      [data addObject:[d objectForKey:@"timeStamp"]];
    }
    

    Block enumerator 方法:

    NSMutableArray *data = [[NSMutableArray alloc] initWithCapacity:array.count];
    [objects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
      [data addObject:[obj objectForKey:@"timeStamp"]];
    }];
    

    无论哪种方式,“数据”都只包含一个 NSDate 实例数组。

    【讨论】:

    • 你能检查一下我发布的另一个答案中的 cmets,看看你是否知道发生了什么?谢谢。
    • @Jon,不确定您的意思,我在您的其他问题或此问题的其他地方没有看到任何新的 cmets。你能澄清一下吗?
    • 关于 Anurag 提供的答案,我们正在讨论一个我们无法解决的问题。
    【解决方案3】:

    要得到你想要的数组类型,你可以这样做:

    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (int n = 0; n < [data count]; n++) // data array 
     {  
        NSMutableArray *array = [[NSMutableArray alloc] init];
        array = [NSMutableArray arrayWithObjects:[[data objectAtIndex:n] valueForKey:@"timeStamp"] ,nil];
       if ([array count] != 0) {
        [newArray addObject:[array objectAtIndex:0]];
        }
      }
     [array release];
    

    希望对你有帮助!!

    ~马诺杰

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多