如何通过方法返回传递NSMutableArray。
我让它传递数组“spaces”,所以10个对象的数组传递10个块,但这些对象中没有包含任何信息。
提前致谢
编辑:基本上我创建了另一个包含路径信息的类,因为我的控制器有点混乱。所以我想要这个新类调用返回NSMutableArray的“create”方法。数组在路径类中很好地创建,但是当return语句触发时,它只传递空格而不是值,甚至是指针。
目前正是
return path;
我试过
return &path;
而且这种情况不合时宜。
Edit2:不幸的是,这是我遇到的问题。
仍在崩溃
致电
newNode = [newNode copy];
导致崩溃
答案 0 :(得分:6)
- (NSMutableArray *) mutableFloobizwits {
NSMutableArray *array = [NSMutableArray array];
for (NSInteger i = 0; i < TheAnswerToTheUltimateQuestion; ++i) {
void(^MyBlock)(void) = ^{
NSLog(@"captured i: %ld", i);
};
MyBlock = [MyBlock copy]; //move the block from off the stack and onto the heap
[array addObject:[Floobizwit floobizwithWithBlock:MyBlock]];
[MyBlock release]; //the Floobizwit should've -retained the block, so we release it
}
return array;
}
答案 1 :(得分:1)
我会设置另一个返回路径对象数组的类,如下所示:
@implementation PathFactory
- (NSMutableArray*) create
{
// In your PathFactory object you create an array and make it autorelease so
// it becomes the callers responsibility to free the memory
NSMutableArray * pathArray = [[[NSMutableArray alloc] init] autorelease];
// Create a bunch of PathObject objects and add them to the mutable array
// also set these to autorelease because the NSMutableArray will retain objects
// added to the collection (ie It is the NSMutableArray's responsibility to ensure
// the objects remain allocated).
for (int i = 0; i < numberOfPaths; i++)
[pathArray addObject:[[[PathObject alloc] init] autorelease]];
// Just return the pointer to the NSMutableArray. The caller will need to
// call the retain message on the pointer it gets back (see next)
return pathArray;
}
@end
所以在你的来电代码中:
// create a tempory PathFactory (autorelease will make sure it is cleaned up when we
// are finished here)
PathFactory * newPathFactory = [[[PathFactory alloc] init] autorelease];
// grab the new array of Path objects and retain the memory. _newPathArray
// is a member of this class that you will need to release later.
_newPathArray = [[newPathFactory create] retain];