2011-04-30 28 views
0

我有一个字符串(titleName)存储在一个类(newNoteBook)存储在一个数组(myLibrary)。我试图访问它,但我只在日志中打印(空)。如何访问存储在数组中的类中的字符串?

我在做什么错?

-(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) 
} 

没有什么花哨的在我的课......简单地说:

@interface NoteBook : NSObject { 

NSString *titleName; } 


@property (nonatomic, retain) NSString *titleName; 
@end 

@implementation NoteBook 
@synthesize titleName; 

回答

1

可能的原因:

  • myLibrary(实例变量)是nil;
  • self.myLibrarynil或其后台实例变量不是myLibrary;
  • [self.myLibrary objectAtIndex:0]newNoteBook不同,因为self.myLibrary中至少有一个其他元素。

编辑:你需要创建一个新的可变数组,并将其分配给你的财产/实例变量myLibrary

self.myLibrary = [NSMutableArray array]; 

myLibrary = [[NSMutableArray alloc] init]; 

,你应该这取决于你的班级如何使用。如果你的类的实例应该始终有有效的myLibrary,一个好地方这样做是-init

- (id)init { 
    self = [super init]; 
    if (self) { 
     myLibrary = [[NSMutableArray alloc] init]; 
    } 
    return self; 
} 

另外,如果你想懒洋洋地创建myLibrary只有当执行-setupLibrary,该方法创建它:

-(void) setupLibrary { 
    self.myLibrary = [NSMutableArray array]; 

    NoteBook *newNoteBook = [[NoteBook alloc] init]; 
    … 
} 

不要忘了释放它在你的-dealloc方法:

- (void)dealloc { 
    [myLibrary release]; 
    [super dealloc]; 
} 
+0

谢谢,但我该如何实现myLibrary或self.myLibrary不是零?到目前为止,myLibrary所做的一切都是我在头文件中声明了它为'NSMutableArray * myLibrary; @property(nonatomic,retain)NSMutableArray * myLibrary;'和实现'@synthesize myLibrary;'。至于第三个可能的原因:这是第一个添加到myLibrary的对象,所以我想不能有另一个。对不起,如果这是基本的,但我不明白。非常感谢你的帮助! – 2011-04-30 09:31:52

+0

刚解决它...它必须是myLibrary = [[NSMutableArray alloc] init]; ... 我早该知道! – 2011-04-30 09:33:49

+0

还要感谢关于不需要类型转换的说明......它看起来太复杂了。 – 2011-04-30 09:36:53

2

试试这个

NSLog(@"titleName:%@", ((NoteBook *)[self.myLibrary objectAtIndex:0]).titleName); 
+1

由于'-objectAtIndex:'是'id'的返回类型,所以不需要类型转换。 – 2011-04-30 09:32:22

1

我觉得你不是类型从数组铸造对象 -

NSLog(@"titleName:%@", [(NoteBook*)[self.myLibrary objectAtIndex:0] titleName]); 

和添加对象之前,您应该ALLOC你的阵列 -

myLibrary = [[NSMutableArray alloc] init]; 
+0

由于'-objectAtIndex:'是'id'的返回类型,所以不需要类型转换。 – 2011-04-30 09:32:28

+0

谢谢,我当然没有分配myLibrary!谢谢你的帮助。至于类型转换,NSLog(@“titleName:%@”,[[self.myLibrary objectAtIndex:0] titleName]);工作得很好,看起来(在我的初学者眼里)比你所说的要复杂一点? – 2011-04-30 09:34:58

1
NSLog(@"titleName:%@", [self.myLibrary objectAtIndex:0].titleName); 

正如他们在不需要施放之前所说的那样是正确的。

相关问题