I just wrote a delegate method, that shall return an array, I’ve created inside this method. Here is the code for that:
- (NSArray *) receivedString:(NSString *)rx{
NSString *portsetting = [[NSString alloc] init];
NSMutableArray *portArray = [[NSMutableArray alloc] initWithCapacity:[portsetting
length]];
portsetting = rx;
for (int i = 0; i < [portsetting length]; i++)
{
NSString *ichar = [NSString stringWithFormat:@"%c",[portsetting
characterAtIndex:i]];
[portArray addObject:ichar];
}
return portArray;
}
This delegate method is part of a library I’ve imported, an is not called by myself, but by the program searching for that method in my code. So far so good…. everything is working fine.
but here is the thing. I would like to get access to this returned array in my code, but I don’t want to call the method itself, because I don’t have any input values for that. This is all handled by the “program”… difficult to explain myself.
So after the method has been called, I would like to get access to this array, maybe by a method I would have written myself. But I don’t have a clue so far, how to do that…… Can someone give me a helping hand?
Is it necessary to init the array outside this function to get access to it? And how would I implement that? In the init-part of the code?
is there a way to make a copy of this array in another method?
Thank you
Sebastian
In your class (the class that conforms to protocol and receives the callback), declare an instance variable and property for an NSMutableArray (or you could cast it as an array if it won’t change again after you first receive it).
When your delegate method is called, assign your portArray to your class property before you return. Then your class instance has a reference to the portArray that can accessed by any method in your class. You don’t need to explicitly allocate/init an array for this, because you already have the array in memory by the time your callback method is finishing – assigning the array to your class property retains the it, thus asserting ownership beyond the scope of the delegate callback.
You could call your own method from within the delegate callback (receivedString), and it would have access to your array.
In your header (myClass.h):
In your implementation (myClass.m)
A final option would be just to pass the array to your own method directly before you return, avoiding the need to define ivars and properties, but requiring you to manage the memory of the array yourself: