got*_*tye 0 iphone properties header
我想实现一个可以由我的项目的两个类使用的类.
一个是操纵'NewsRecord'对象.一个是操纵'GalleriesRecord'对象.
在另一个类中,我可以使用这两个对象中的一个,所以我做了类似的事情:
// header class
id myNewsRecordOrGalleriesRecord;
// class.m
// NewsRecord and GalleriesRecord have both the title property
NSLog(myNewsRecordOrGalleriesRecord.title);
Run Code Online (Sandbox Code Playgroud)
我得到:
error : request for member 'title' in something not a structure or union
Run Code Online (Sandbox Code Playgroud)
任何想法:D?
谢谢.
高堤耶
我该怎么办呢?
您不能在id
类型上使用点语法,因为编译器无法知道什么x.foo
意思(声明的属性可能使getter成为不同的名称,例如view.enabled -> [view isEnabled]
).
因此,您需要使用
[myNewsRecordOrGalleriesRecord title]
Run Code Online (Sandbox Code Playgroud)
要么
((NewsRecord*)myNewsRecordOrGalleriesRecord).title
Run Code Online (Sandbox Code Playgroud)
如果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.
Run Code Online (Sandbox Code Playgroud)
顺便说一句,不要使用NSLog(xxx);
,这很容易发生格式字符串攻击而你无法确定xxx
是否真的是一个NSString.请NSLog(@"%@", xxx);
改用.
归档时间: |
|
查看次数: |
333 次 |
最近记录: |