2010-04-20 81 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"]);