我对类和对象很陌生,我有一个问题:
- 我正在跟踪可以由 textFields 输入的书籍。
- 每本书 3 个属性:标题、作者和描述。
我想要做的是将所有书籍对象放在一个NSMutableArray
名为:Collection 中。(目前只有一本书(objectAtIndex:0
)目前正在工作,但是当我试图将它们吐出来时,我只得到了这本书的描述。我很想得到所有的项目(标题、作者、描述)。
我一直想知道的是:我应该创建一个新的(集合)类,例如名为 BookCollection 并在那里创建一个数组吗?但是我将如何初始化它等?
代码如下,欢迎帮助和提示!(大约一个月前开始)
Book.h
#import <Foundation/Foundation.h>
@interface Book : NSObject
@property(nonatomic,strong)NSString* title;
@property(nonatomic,strong)NSString* author;
@property(nonatomic,strong)NSString* description;
-(id)initWithTitle:(NSString*)newTitle withAuthor:(NSString*)newAuthor andDescription:(NSString*)newDesription;
Book.m
#import "Book.h"
@implementation Book
@synthesize title,author,description;
-(id)initWithTitle:(NSString*)newTitle withAuthor:(NSString*)newAuthor andDescription:(NSString*)newDesription{
self = [super init];
if (self) {
title = newTitle;
author = newAuthor;
description = newDesription;
}
return self;
}
@end
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize lblTitle,lblAuthor,lblDescription;
@synthesize collection;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
}
- (IBAction)buttonClick:(id)sender {
//alloc the array that will hold the books
collection = [[NSMutableArray alloc]init];
//create a new book
Book *newBook = [[Book alloc]initWithTitle:[lblTitle stringValue] withAuthor:[lblAuthor stringValue] andDescription:[lblDescription stringValue]];
//logging the items of the book
NSLog(@"%@",newBook.description);
NSLog(@"%@",newBook.title);
NSLog(@"%@",newBook.author);
//adding the book to the collection
[collection addObject:newBook];
//logging the book items from the collection
NSLog(@"%@",[collection objectAtIndex:0]);
//problem... only logs 1 item from the object...
}
@end
AppDelegate.h
#import <Cocoa/Cocoa.h>
#import "Book.h"
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property(nonatomic,strong)NSMutableArray *collection;
@property (assign) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSTextField *lblTitle;
@property (weak) IBOutlet NSTextField *lblAuthor;
@property (weak) IBOutlet NSTextField *lblDescription;
- (IBAction)buttonClick:(id)sender;
@end