我有几个类
:Book
、Publisher
和。Author
Genre
所以这里是主类Book.h:
#import "Publisher.h"
#import "Author.h"
#import "Genre.h"
@interface Book : NSObject
@property (nonatomic, strong) NSString *bookName;
@property (nonatomic, strong) Author *author;
@property (nonatomic, strong) Publisher *publisher;
@property (nonatomic, weak) Genre *genre;
- (instancetype)initWithBookName:(NSString *)name andAuthorName:(NSString *)authorName
andPublisher:(NSString *)publisherName andGenreName:(__strong NSString *)genreName;
- (NSString *)description;
@end
和他的实现Book.m:
#import "Genre.h"
#import "Book.h"
#import <Foundation/Foundation.h>
@implementation Book
- (instancetype)initWithBookName:(NSString *)name andAuthorName:(NSString *)authorName
andPublisher:(NSString *)publisherName andGenreName:(__strong NSString *)genreName{
self = [super init];
if (self) {
_bookName = [name copy];
_author = [[Author alloc] initWithAuthorName:authorName];
_publisher = [[Publisher alloc] initWithPublisherName:publisherName];
_genre = [[Genre alloc] initWithGenreName:genreName];
}
return self;
}
- (instancetype)init {
return [self initWithBookName:@"unnamed" andAuthorName:@"unnamed" andPublisher:@"unnamed" andGenreName:@"unnamed"];
}
- (NSString *)description {
return [NSString stringWithFormat: @"Book: %@, Author: %@, Genre: %@", self.bookName, self.author, self.genre];
}
@end
我有委托类 - Genre,所以为了避免强引用循环, aBook
的Genre
属性必须是weak。
此时在 Book.m 初始化程序中:
_genre = [[Genre alloc] initWithGenreName:genreName];
它将为零,因为Genre
实例将在分配后立即被释放。
根据 Dan 的评论,这是我的 Genre.h:
#import <Foundation/Foundation.h>
@class Book;
@interface Genre : NSObject
@property (nonatomic, strong) NSString *genreName;
@property (nonatomic, strong) NSArray <Book *> *books;
- (instancetype)initWithGenreName:(NSString *)name andBooks:(NSArray <Book *>*)books;
- (instancetype)initWithGenreName:(NSString *)name;
- (NSString *)description;
@end
我的问题是“在弱属性流派中存储流派对象(流派名称->流派构造函数->流派对象)的最佳方法是什么?如何在不使用构造函数分配给弱属性的情况下存储它?”。
解决方案:在我的情况下,它是类型的集合,我将我的弱属性引用引用到我的集合中的一个对象。
Genre * genre1 = [[Genre alloc]initWithGenreName:@"Comedy"];
Genre * genre2 = [[Genre alloc]initWithGenreName:@"Drama"];
Genre * genre3 = [[Genre alloc]initWithGenreName:@"Fantastic"];
Genre * genre4 = [[Genre alloc]initWithGenreName:@"National"];
NSArray <Genre*> *genres = @[genre1, genre2, genre3, genre4];
Book *book1 = [[Book alloc] initWithBookName:@"Book #3!" andAuthorName:@"Grinch Burs" andPublisher:@"Ableton" andGenre:[genres objectAtIndex:0]];