Reputation: 7911
I created a Food
object that I'd like to be able to set and get attributes of (such as time
). For some reason I'm allowed to set attributes, but I am not able to the get attributes. I receive the following error by simply calling food.time
Property 'time' not found on object of type 'conts __strong id'
I'm not sure if the problem is with putting it in, and then retrieving it from, an array or if it is how my object class is defined. In this example I've simplified it so that you can see how I'm using it.
Some controller (with other methods not shown here)
#import "Food.h"
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *foodArray = @[firstFood];
for (id food in foodArray) {
UILabel *foodLabel = [[UILabel alloc]
initWithFrame:CGRectMake(10, 180, self.view.frame.size.width-20, 50)];
foodLabel.backgroundColor = [UIColor clearColor];
foodLabel.text = food.time; // This line causes error
foodLabel.textColor = [UIColor blackColor];
[foodLabel setFont:[UIFont fontWithName:@"Courier" size:14]];
[self.view addSubview:foodLabel];
}
}
Food.h
#import <Foundation/Foundation.h>
@interface Food : NSObject
@property (strong, nonatomic) NSString *time;
@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSString *description;
@property (strong, nonatomic) NSString *place;
@end
Food.m
#import "Food.h"
@implementation Food
@end
Upvotes: 0
Views: 82
Reputation: 26058
As far as the compiler knows food
is just a generic NSObject pointer. You either need to cast it to a Food
object, or just change your definition within the for loop.
for (Food *food in foodArray) {
//...etc
}
That is assuming firstFood
is actually a Food
object, since you do not show it's definition in your snippet.
If you don't want to change the type, you can send any message to id, and let it figure out at run-time whether it is valid:
foodLabel.text = [food time];
would also be valid, but you are unable to use the dot syntax on an object of type id
, either cast it or use the standard bracket syntax (which will fail at run-time if that object does not respond to that message).
Upvotes: 3