简体   繁体   中英

How do I loop through an NSArray of Custom Objects

I created an NSArray from a CoreData fetch like so:

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

In a tableview I used this code to get my custom objects:

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

But Im now in another viewcontroller, trying to plot the data on a mapkit, so in the plotting method i originally did this because i was getting an array from a plist file. But now my array is of custom Holiday objects so this doesnt work anymore:

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];

}

My dictionary log prints out this:

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>)"

Which means its an array of holiday objects.

How do I get each object in my for loop since Im using enumeration instead of a traditional for i = 0; i<count; i++ for i = 0; i<count; i++ for i = 0; i<count; i++ ?

It looks like you are using a custom object with CoreData, so it will be returning an array of your class.

Does this work:

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

If CoreData is not using your custom object, it will return an array of NSManagedObject, in which case use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM