我已经启动了一个 Master Detail 应用程序,并且没有修改生成的代码。我创建并添加了两个额外的类:一个书籍类(包含一个用于标题、作者和摘要的 NSString)和一个数据控制器类(包含一个可变数组来存储书籍)。
在阅读 Apple doc 和其他文档后,我对 @property 属性的理解是这样的:
- strong - 默认,创建对象的所有权
- 弱 - 强的替代品,用于避免保留循环
- 复制 - 创建现有对象的副本并获得该对象的所有权
- nonatomic - 忽略任何类型的线程安全
当使用 copy 属性声明 @property AJKBook 时,此代码在 addBookToList 中引发分段错误,我不明白为什么。
@interface AJKBookDataController ()
// when current book uses the copy attribute code seg faults in addBookToList
@property (nonatomic) AJKBook *currentBook;
@property (nonatomic, copy) NSString *currentValue;
- (void)populateBookList;
- (void)addBookToBookList;
@end
@implementation AJKBookDataController
- (id)init
{
self = [super init];
if (self) {
_bookList = [[NSMutableArray alloc] init];
_currentBook = [[AJKBook alloc] init];
_currentValue = [[NSString alloc] init];
[self populateBookList];
return self;
}
return nil;
}
- (void)setBookList:(NSMutableArray *)bookList
{
// this bit of code ensures bookList stays mutable
if (_bookList != bookList) {
_bookList = [bookList mutableCopy];
}
}
- (void)populateBookList
{
NSURL *url = [NSURL URLWithString:@"https://sites.google.com/site/iphonesdktutorials/xml/Books.xml"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser parse];
NSLog(@"%@", [self.bookList description]);
}
- (void)addBookToBookList
{
[self.bookList addObject:self.currentBook];
self.currentBook = [[AJKBook alloc] init];
}
...
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"title"]) {
// [self.currentBook title:self.currentValue];
self.currentBook.title = self.currentValue;
} else if ([elementName isEqualToString:@"author"]) {
self.currentBook.author = self.currentValue;
} else if ([elementName isEqualToString:@"summary"]) {
self.currentBook.summary = self.currentValue;
} else if ([elementName isEqualToString:@"Book"]) {
[self addBookToBookList];
}
self.currentValue = [NSString stringWithFormat:@""];
}
@end