Use of type 'id' in cocoa class
I want to implement a class which can be used by two classes of my proje开发者_运维问答ct.
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 ?
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.
- Try accessing the title of your record like
[myNewsRecordOrGalleriesRecord title];
- If you're going to be doing a lot of this type of thing (accessing common methods in two classes) you would probably benefit significantly from either creating an abstract superclass that both
NewsRecord
andGalleriesRecord
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.
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"] );
精彩评论