我有一个NSMutableArray,我用下面的代码填充,但是当我在下面的代码中访问数组时,数组是空的?
此代码填充数组
NSMutableArray *videos;
- (void)viewDidLoad
{
[super viewDidLoad];
...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"kingdb5.sqlite"];
db = [FMDatabase databaseWithPath:writableDBPath];
if (![db open]) {
return;
}
FMResultSet *s = [db executeQuery:@"SELECT * FROM mediaVideos"];
if ([db hadError]) {
NSLog(@"DB Error %d: %@", [db lastErrorCode], [db lastErrorMessage]);
}
while ([s next]) {
NSString *url = [s stringForColumnIndex:1];
NSLog(url);
[videos addObject:url];
}
...
}
NSLog(url)打印出正确数量的网址(也是正确的等)
然后当用户按下按钮时访问该数组:
- (IBAction)playbutton_onclick:(id)sender {
for (NSString *s in videos){
NSLog(s);
}
NSString *file = [videos objectAtIndex:2];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/Videos/%@", file]];
NSLog(@"Now playing: %@", dataPath);
NSURL *url = [NSURL fileURLWithPath:dataPath];
MPMoviePlayerViewController* viewController = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
[self presentMoviePlayerViewControllerAnimated:viewController];
}
此时数组为空,for循环不打印任何内容,并且在索引点获取对象返回null
答案 0 :(得分:1)
首先使videos
成为类的实例变量或属性:
@interface MyClass : UIViewController
@property (nonatomic) NSMutableArray *videos;
@end
然后在实现文件中分配并初始化它:
- (void)viewDidLoad
{
[super viewDidLoad];
self.videos = [NSMutableArray new];
...
}
并将videos
的所有引用更改为self.videos
。
答案 1 :(得分:0)
在viewDidLoad的开头,您必须分配数组:
videos = [[NSMutableArray alloc] init];
为了获得最佳实践,您应该将其作为属性并将其称为self.videos。 请参阅trojanfoe添加的答案。