好吧,我知道我是obj-c的新手,但是出于所有意图和目的,下面的SEEMS应该有效:

songCollection = [[NSMutableArray alloc] init];
    [songCollection addObject:@"test"];
    //Array is init, and I can see it in the debugger.
    songCollection = [GeneralFunctions getJSONAsArray:@"library"];
    // I can see the expected data in the debugger after this.
    [songCollection retain];
    NSLog(@"%@", [songCollection objectAtIndex:0]);
        // Crashes here due to the array not responding to the selector. Also, the array is now empty.
    //NSLog(@"%@", songCollection);
    NSArray * songList = [songCollection objectAtIndex:1];
    NSLog(@"%@", songList);

我希望有人能在这里帮助我,我正撞在墙上!

有帮助吗?

解决方案

songCollection 最初是一个NSMutableArray,但是你用 [GeneralFunctions getJSONAsArray:@" library"] 返回的内容覆盖了它。不管是什么,它可能不是阵列。

顺便说一下,你在这里泄漏一个数组。

其他提示

让我们将您的代码逐步分开。

songCollection = [[NSMutableArray alloc] init];

分配一个新的空NSMutableArray。

[songCollection addObject:@"test"];

添加NSString @" test"到NSMutableArray songCollection

songCollection = [GeneralFunctions getJSONAsArray:@"library"];

抛弃你对你创建的可变数组的引用(从而泄漏内存)并为你提供一个新指针,指向你尚未拥有的东西。

[songCollection retain];

这很好,你取得了songCollection的所有权。由于这有效,你知道getJSONAsArray返回nil或NSObject。

NSLog(@"%@", [songCollection objectAtIndex:0]);
// Crashes here due to the array not responding to the selector. Also, the array is now empty.

很明显,songCollection既不是nil,也不是NSArray(可变或其他)。检查GeneralFunctions getJSONAsArray的文档或签名,看看它实际返回的内容。

//NSLog(@"%@", songCollection);

这个输出是什么 - 应该告诉你songCollection实际上是什么。

假设您弄清楚为什么getJSONAsArray没有返回NSArray,您可以使用

将NSArray转换为NSMutableArray
songCollection = [[GeneralFunctions getJSONAsArray:@"library"] mutableCopy];
// You now own songCollection

songCollection = [[NSMutableArray alloc] init];
// You now own songCollection
[songCollection addObjectsFromArray:[GeneralFunctions getJSONAsArray:@"library"];

[GeneralFunctions getJSONAsArray:@" library"]实际上是否返回NSArray?

在您使用该行重新分配之前,您还忘记发布songCollection。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top