我有几个类: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
我有委托类-类型,所以要避免强引用周期,aBook
的Genre
属性必须是弱的。
此时在Book.m初始化程序中:
_genre = [[Genre alloc] initWithGenreName:genreName];
它为nil,因为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
我的问题是“在弱属性流派中存储流派对象(genreName->流派构造函数->流派对象)的最佳方法是什么?如何在不使用构造函数分配弱属性的情况下存储它?”
解决方案:就我而言,这是流派的集合,而我的弱属性引用是我的集合中的一个对象。
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]];
要记住的规则是-强属性增加引用计数,而弱属性不增加-当引用计数变为0时,将释放适当的属性。因此,对于Genre-在您的代码中,没有强引用,因此将其释放。解决的方法实际上是让流派被另一个阶级“拥有”。此类将管理类型,创建它们并对其进行强有力的引用,例如在一系列类型中。您的“强”类型将与初始化程序一起传入,然后弱引用是正确的方法,可以防止保留周期,但是通过Genre属性已经具有的强属性可以防止取消分配-这有意义吗?
从某种意义上说,将您的对象视为需要一个“所有者”类是有意义的,在该类中定义了使它们保持活动状态的强引用。然后,当传递给其他类(如Book类)时,这些类的引用将很弱,这将阻止您所说的保留周期。书类不是所有者,但其他人不是-因此它不会消失。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句