Reputation: 958
I want to implement a class which can be used by two classes of my project.
One is manipulating 'NewsRecord' objects. One is manipulating 'GalleriesRecord' objects.
In another class, I may use one of the two objects so i do something like that :
// header class
id myNewsRecordOrGalleriesRecord;
// class.m
// NewsRecord and GalleriesRecord have both the title property
NSLog(myNewsRecordOrGalleriesRecord.title);
and i get :
error : request for member 'title' in something not a structure or union
any ideas :D ?
Thanks.
Gotye
How am I supposed to do it ?
Upvotes: 0
Views: 346
Reputation: 29862
The compiler is not happy since an id
is actually a NSObject
instance, which doesn't have a title
property.
If your object is KVC compliant, you can use the valueForKey
method:
NSLog( [myNewsRecordOrGalleriesRecord valueForKey:@"title"] );
Upvotes: 0
Reputation: 49364
[myNewsRecordOrGalleriesRecord title];
NewsRecord
and GalleriesRecord
can inherit from (if they'll be sharing a lot of code) or creating a protocol they both can adhere to (if they'll be sharing method names but not code.Upvotes: 0
Reputation: 523344
You can't use dot syntax on id
types because the compiler cannot know what x.foo
means (the declared property may make the getter a different name, e.g. view.enabled -> [view isEnabled]
).
Therefore, you need to use
[myNewsRecordOrGalleriesRecord title]
or
((NewsRecord*)myNewsRecordOrGalleriesRecord).title
If title
and more stuffs are common properties of those two classes, you may want to declare a protocol.
@protocol Record
@property(retain,nonatomic) NSString* title;
...
@end
@interface NewsRecord : NSObject<Record> { ... }
...
@end
@interface GalleriesRecord : NSObject<Record> { ... }
...
@end
...
id<Record> myNewsRecordOrGalleriesRecord;
...
myNewsRecordOrGalleriesRecord.title; // fine, compiler knows the title property exists.
BTW, don't use NSLog(xxx);
, which is prone to format-string attack and you can't be certain xxx
is really an NSString. Use NSLog(@"%@", xxx);
instead.
Upvotes: 6