开发者

Problems with getting data from a class

I guess this is quite basic, but I am struggling with getting data (in this case a simple string) from a class.

My class is quite simple; it looks like this:

    @interface myBook : NSObject {

    NSString开发者_如何学编程 *titleName;
    NSString *titleColour;

}

And then I have all the @property and @synthesise calls. I import this (#import myBook.h) in my viewController, where I want to add books to my library. So I have this set of variables to control my library:

    NSMutableArray *myLibrary;
NSUInteger currentBookNumber;
myBook *currentBook;

and:

@property (nonatomic, retain) NSMutableArray *myLibrary;
@property (nonatomic, assign) NSUInteger currentBookNumber;
@property (nonatomic, readonly) NoteBook *currentBook;

I then set up my library like so:

-(void) setupLibrary {

myBook *newBook = [[myBook alloc] init];

newBook.titleName = @"Test";
newBook.titleColour = @"orange";

[myLibrary addObject:newBook];
[myLibrary addObject:newBook];
[myLibrary addObject:newBook];

currentBookNumber = 0;

}

In order to get data from the current book I have the following method:

-(NmyBook *) currentBook {


myBook *thisBk = [self.myLibrary
                        objectAtIndex:self.currentBookNumber];
return thisBk;

}

Now my problem is that if I want to get data from myLibrary and call this in my viewDidLoad, I will only get nil for the title... where did I go wrong?

- (void)viewDidLoad {

[self setupLibrary];
NSLog(@"TitleName:%@", currentBook.titleName);


Issues I see:

Number 1: I hope the currentBook method return type is a typo. I'm seeing a -(NmyBook *)... shouldn't that be a - (myBook *)?

Number 2: You never initialized the currentBook object. Before you call the NSLog, you should go

currentBook = [self currentBook];

Where [self currentBook] calls the currentBook method and sets the returned object as the currentBook object.

Finally, try not having the same names for variables and methods :)

Hope that helps.


You have to use self.currentBook.titleName. currentBook.titleName won't trigger your accessor.

By the way, your setupLibrary is leaking. You'll want to add [newBook release] after the last [myLibrary addObject:newBook] call.


You had called one property currentBook and one method currentBook : Normally it works but you should call the method getCurrentBook;

and the right to access to a property in his class is to use :

[self.theProperty method];

Use :

newBook.titleName = [NSString stringWithFormat:@"Test"];
newBook.titleColor = [NSString stringWithFormat:@"Orange"];

After you can call :

NSLog(@"TitleName:%@", self.currentBook.titleName);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜