【发布时间】:2013-09-28 05:41:45
【问题描述】:
我对类和对象很陌生,我有一个问题:
- 我正在跟踪可以通过 textFields 输入的书籍。
- 每本书 3 个属性:标题、作者和说明。
我正在尝试做的是在 NSMutableArray 中获取书籍的所有对象,称为:集合。
(目前只有 1 本书 (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
【问题讨论】:
-
它非常简单 @Ben Vertonghen 只需从您的 Click 方法中删除
collection = [[NSMutableArray alloc]init];行就可以了。在applicationDidFinishLaunching方法中初始化您的数组。进行此更改,您就完成了。 -
您不应该使用“描述”作为属性名称,因为至少会与在 NSObject 中定义并在许多方法中被覆盖的标准
description方法混淆。您希望description以“正常”方式工作,并转储对象的表示。 -
请记住,@HotLicks!谢谢!
标签: objective-c class object nsmutablearray