【问题标题】:How do I loop through an NSArray of Custom Objects如何循环遍历自定义对象的 NSArray
【发布时间】:2013-01-03 16:00:38
【问题描述】:

我从 CoreData 获取中创建了一个 NSArray,如下所示:

self.farSiman = [self.managedObjectContext executeFetchRequest:request error:&error];

在表格视图中,我使用此代码来获取我的自定义对象:

Holiday *holiday = [self.dates objectAtIndex:indexPath.row];
cell.nameLabel.text = holiday.name;

但我现在在另一个视图控制器中,试图在 mapkit 上绘制数据,所以在绘图方法中我最初这样做是因为我从 plist 文件中获取了一个数组。但是现在我的数组是自定义的 Holiday 对象,所以这不再起作用了:

NSLog(@"dictionary is %@", self.farSiman);

for (NSDictionary * dict in self.farSiman) {


    NSNumber * latitude = [dict objectForKey:@"latitude"];
    NSNumber * longitude = [dict objectForKey:@"longitude"];
    NSString * storeDescription = [dict objectForKey:@"name"];
    NSString * address = [dict objectForKey:@"address"];
    NSLog(@"logging location %@", storeDescription);
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = latitude.doubleValue;
    coordinate.longitude = longitude.doubleValue;
    MyLocation *annotation = [[MyLocation alloc] initWithName:storeDescription address:address coordinate:coordinate];
    [_mapView addAnnotation:annotation];

}

我的字典日志打印出这个:

dictionary is (
"<Holiday: 0x838bc80> (entity: Holiday; id: 0x838ca60 <x-coredata://E41B0CCD-2F03-4C4F-B054-18537096771C/Holiday/p1> ; data: <fault>)",
"<Holiday: 0x838e330> (entity: Holiday; id: 0x838ca70 <x-coredata://E41B0CCD-2F03-4C4F-B054-18537096771C/Holiday/p2> ; data: <fault>)"

这意味着它是一组假日对象。

由于我使用枚举而不是传统的 for i = 0; i&lt;count; i++,如何在我的 for 循环中获取每个对象?

【问题讨论】:

    标签: objective-c ios nsarray enumeration


    【解决方案1】:

    看起来您正在使用带有 CoreData 的自定义对象,因此它将返回您的类的数组。

    这行得通吗:

    for (Holiday *holiday in self.farSiman) {
        // your code here
        // [holiday foo]
    }
    

    如果 CoreData 没有使用你的自定义对象,它会返回一个 NSManagedObject 的数组,在这种情况下使用这个:

    for (NSManagedObject *holiday in self.farSiman) {
        // your code here
        //[holiday valueForKey:@"foo"]
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 2020-06-09
      相关资源
      最近更新 更多