是的,一个类拥有一个实例变量(您所称的成员变量的 ObjC 术语)或属性是完全可以接受的,其类型是其自身的子类。
这是一个简单的、可编译的程序,它演示了您在 Objective-C 中所要求的内容:
#import <Foundation/Foundation.h>
@class Song;
@interface Album : NSObject
@property (strong) NSString *artist;
@property (strong) NSString *title;
@property (strong) NSArray *songs;
@property (strong) Song *bestSong;
@end
@interface Song : Album
@property (weak) Album *album;
@property NSTimeInterval duration;
@end
@implementation Album
@end
@implementation Song
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
Album *album = [[Album alloc] init];
Song *song1 = [[Song alloc] init];
Song *song2 = [[Song alloc] init];
album.songs = @[song1, song2];
album.bestSong = song1;
song1.album = album;
song2.album = album;
NSLog(@"Album: %@", album);
NSLog(@"songs: %@", album.songs);
NSLog(@"bestSong: %@", album.bestSong);
}
}
输出:
Album: <Album: 0x7fcc3a40a3e0>
songs: (
"<Song: 0x7fcc3a40a5e0>",
"<Song: 0x7fcc3a40a670>"
)
bestSong: <Song: 0x7fcc3a40a5e0> bestSong: <Song: 0x7ff48840a580>