views:

57

answers:

3

Hey guys,

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 ?

+6  A: 

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.

KennyTM
[myNewsRecordOrGalleriesRecord title] is working great ;)
gotye
Also, thanks for the quick AND nice answer !
gotye
A: 
  1. Try accessing the title of your record like [myNewsRecordOrGalleriesRecord title];
  2. 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 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.
kubi
A: 

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"] );
Martin Cote