【问题标题】:EXEC_BAD_ACCESS error, memory management issuesEXC_BAD_ACCESS 错误,内存管理问题
【发布时间】:2011-09-03 01:44:51
【问题描述】:

我了解到此错误来自内存管理问题,例如向已释放的对象发送消息。在第二个“for”部分的第一行中,我在评论“输出有关 'info' 数组中歌曲的信息”之后立即收到错误消息。 info 数组是否没有存储我在第一个“for”部分中提供的对象?

还有其他想法吗?

MPMediaQuery *query = [[MPMediaQuery alloc] init]; //query iPod library
NSMutableArray *info; //create array to hold songs that fit
NSArray *allSongs = [query collections];

//only add those songs which have not
//been played since last login

for (MPMediaItem *recent in allSongs) {
    NSDate *lastPlayed = [recent valueForProperty:MPMediaItemPropertyLastPlayedDate];
    BOOL uploadInfo = [[PlayedSinceLastLogin alloc] initWithLastPlayedDateOfSong:lastPlayed] ;
    if (uploadInfo == YES) {
        [info addObject:recent];
    }
}

//output information about songs
//in the 'info' array

for (MPMediaItem *played in info) {
    NSString *playCount = [played valueForProperty:MPMediaItemPropertyPlayCount];
    NSString *lastPlayed = [played valueForProperty:MPMediaItemPropertyLastPlayedDate];
    NSString *songTitle =
    [played valueForProperty: MPMediaItemPropertyTitle];
    NSString *artistName =
    [played valueForProperty: MPMediaItemPropertyArtist];
    NSString *albumName =
    [played valueForProperty: MPMediaItemPropertyAlbumTitle];
    NSLog (@"\n %@ by %@, from album %@, played since last login.\nLast Played:%@.\nTotal Play Count: %@.", songTitle, artistName, albumName, lastPlayed,playCount);

}

【问题讨论】:

    标签: iphone objective-c xcode memory-management


    【解决方案1】:

    看起来你实际上并没有为 info 创建一个 NSMutableArray 的实例来指向,所以错误的访问错误可能是由于试图将一些随机的内存位视为初始化对象.

    改变

    NSMutableArray *info;
    

    NSMutableArray *info = [NSMutableArray array];
    

    【讨论】:

    • 附带说明,如果你真的很偏执,如果你还没有准备好分配一个值,那么 nil-init 是个好主意:NSMutableArray *info = nil;
    • 非常好!我认为在方法从 - 变为 + 之前,它以前是一个 ivar。非常感谢!
    • 我是否还必须创建 UITextView 对象的实例?当我尝试将 textView.Text 更改为我刚刚创建的字符串时,我遇到了类似的错误。
    • 是的,所有对象都必须在某个地方创建;你永远不能只声明和使用它们。很多时候,当您加载 nib 文件时,运行时会创建 UITextView 对象,但如果不是,则必须手动创建。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多