i have string (titlename) stored in class (newnotebook) stored in array (mylibrary). trying access it, (null) printed in log.
what doing wrong?
-(void) setuplibrary { notebook *newnotebook = [[notebook alloc] init]; newnotebook.titlename = @"test"; nslog(@"titlename:%@", newnotebook.titlename); // prints test in log [mylibrary addobject:newnotebook]; nslog(@"titlename:%@", [[self.mylibrary objectatindex:0] titlename]); // prints (null) in log) } there nothing fancy in class... simply:
@interface notebook : nsobject { nsstring *titlename; } @property (nonatomic, retain) nsstring *titlename; @end @implementation notebook @synthesize titlename;
possible reasons:
mylibrary(the instance variable)nil;self.mylibrarynilor backing instance variable isn’tmylibrary;[self.mylibrary objectatindex:0]not same objectnewnotebookbecause there @ least 1 other element inself.mylibrary.
edit: need create new mutable array , assign property/instance variable mylibrary:
self.mylibrary = [nsmutablearray array]; or
mylibrary = [[nsmutablearray alloc] init]; where should depend on how class used. if instance of class should have valid mylibrary, place in -init:
- (id)init { self = [super init]; if (self) { mylibrary = [[nsmutablearray alloc] init]; } return self; } alternatively, if want lazily create mylibrary when -setuplibrary executed, create in method:
-(void) setuplibrary { self.mylibrary = [nsmutablearray array]; notebook *newnotebook = [[notebook alloc] init]; … } don’t forget release in -dealloc method:
- (void)dealloc { [mylibrary release]; [super dealloc]; }
Comments
Post a Comment