I have a string (titleName) stored in a class (newNoteBook) stored in an array (myLibrary). I was trying to access it, but I only get a (null) printed in the log.
What am I doing wrong?
-(void) setupLibrary {
NoteBook *newNoteBook = [[NoteBook alloc] init];
newNoteBook.titleName = @"TEST";
NSLog(@"titleName:%@", newNoteBook.titleName); // this prints TEST in the log
[myLibrary addObject:newNoteBook];
NSLog(@"开发者_开发技巧titleName:%@", [[self.myLibrary objectAtIndex:0] titleName]); // this prints (null) in the log)
}
There is nothing fancy in my class... simply:
@interface NoteBook : NSObject {
NSString *titleName; }
@property (nonatomic, retain) NSString *titleName;
@end
@implementation NoteBook
@synthesize titleName;
Try this
NSLog(@"titleName:%@", ((NoteBook *)[self.myLibrary objectAtIndex:0]).titleName);
Possible reasons:
myLibrary
(the instance variable) isnil
;self.myLibrary
isnil
or its backing instance variable isn’tmyLibrary
;[self.myLibrary objectAtIndex:0]
is not the same object asnewNoteBook
because there was at least one other element inself.myLibrary
.
Edit: you need to create a new mutable array and assign it to your property/instance variable myLibrary
:
self.myLibrary = [NSMutableArray array];
or
myLibrary = [[NSMutableArray alloc] init];
Where you should this depend on how your class is used. If an instance of your class should always have valid myLibrary
, a good place to do that is in -init
:
- (id)init {
self = [super init];
if (self) {
myLibrary = [[NSMutableArray alloc] init];
}
return self;
}
Alternatively, if you want to lazily create myLibrary
only when -setupLibrary
is executed, create it in that method:
-(void) setupLibrary {
self.myLibrary = [NSMutableArray array];
NoteBook *newNoteBook = [[NoteBook alloc] init];
…
}
Don’t forget to release it in your -dealloc
method:
- (void)dealloc {
[myLibrary release];
[super dealloc];
}
I think you are not type casting object from array -
NSLog(@"titleName:%@", [(NoteBook*)[self.myLibrary objectAtIndex:0] titleName]);
and you should alloc your array before adding object to it -
myLibrary = [[NSMutableArray alloc] init];
NSLog(@"titleName:%@", [self.myLibrary objectAtIndex:0].titleName);
Is correct as they said before you don't need to cast.
精彩评论