2010-04-20 83 views
0

我想实现一个可以由我的项目的两个类使用的类。在可可类中使用'id'类型

一个是操纵'NewsRecord'对象。 一个正在操作'GalleriesRecord'对象。

在另一类,我可以用两个对象之一,所以我做这样的事情:

// header class 
id myNewsRecordOrGalleriesRecord; 

// class.m 
// NewsRecord and GalleriesRecord have both the title property 
NSLog(myNewsRecordOrGalleriesRecord.title); 

,我也得到:

error : request for member 'title' in something not a structure or union 

任何想法:d?

谢谢。

Gotye

我该怎么做呢?

回答

6

您不能在id类型上使用点语法,因为编译器无法知道x.foo的含义(声明的属性可能使getter的名称不同,例如view.enabled -> [view isEnabled])。

因此,你需要使用

[myNewsRecordOrGalleriesRecord title] 

((NewsRecord*)myNewsRecordOrGalleriesRecord).title 

如果title多的东西是这两个类的公共属性,你可能要宣布的协议。

@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,不要使用NSLog(xxx);,这是容易format-string attack,你不能确定xxx真的是一个NSString。改为使用NSLog(@"%@", xxx);

+0

[myNewsRecordOrGalleriesRecord标题]是伟大的工作;) – gotye 2010-04-20 18:30:21

+0

另外,感谢您的快速和漂亮的答案! – gotye 2010-04-20 18:30:54

0
  1. 尝试访问您的记录的标题像[myNewsRecordOrGalleriesRecord title];
  2. 如果你打算做了很多这种类型的东西的(访问常用的方法有两种类),你可能会无论从创建显著受益抽象超两个NewsRecordGalleriesRecord可以(如果它们将分享大量的代码),或创建一个protocol他们都能够坚持(如果他们将分享方法的名称,但不是代码继承。
0

编译器自以来并不开心0实际上是一个NSObject实例,它没有title属性。

如果你的对象是KVC兼容的,你可以使用valueForKey方法:

NSLog([myNewsRecordOrGalleriesRecord valueForKey:@"title"]);