Wed*_*dTM 1 iphone objective-c nsmutablearray
好吧,我知道我是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);
Run Code Online (Sandbox Code Playgroud)
我希望有人能在这里帮助我,我正撞在墙上!
songCollection最初是一个NSMutableArray,但是你用任何返回来覆盖它[GeneralFunctions getJSONAsArray:@"library"].不管是什么,它可能不是一个阵列.
顺便说一下,你在这里泄漏一个数组.
让我们一步一步地分开您的代码.
songCollection = [[NSMutableArray alloc] init];
Run Code Online (Sandbox Code Playgroud)
分配一个新的空NSMutableArray.
[songCollection addObject:@"test"];
Run Code Online (Sandbox Code Playgroud)
将NSString @"test"添加到NSMutableArray songCollection
songCollection = [GeneralFunctions getJSONAsArray:@"library"];
Run Code Online (Sandbox Code Playgroud)
抛弃你对你创建的可变数组的引用(从而泄漏内存),并为你提供一个新指针,指向你尚未拥有的东西.
[songCollection retain];
Run Code Online (Sandbox Code Playgroud)
多数民众赞成,你拥有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.
Run Code Online (Sandbox Code Playgroud)
很明显,songCollection既不是零,也不是NSArray(可变或其他).检查GeneralFunctions getJSONAsArray的文档或签名,看看它实际返回的内容.
//NSLog(@"%@", songCollection);
Run Code Online (Sandbox Code Playgroud)
这个输出是什么 - 应该告诉你songCollection实际上是什么.
假设您弄清楚为什么getJSONAsArray没有返回NSArray,您可以将NSArray转换为NSMutableArray
songCollection = [[GeneralFunctions getJSONAsArray:@"library"] mutableCopy];
// You now own songCollection
Run Code Online (Sandbox Code Playgroud)
要么
songCollection = [[NSMutableArray alloc] init];
// You now own songCollection
[songCollection addObjectsFromArray:[GeneralFunctions getJSONAsArray:@"library"];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7322 次 |
| 最近记录: |