Reputation: 93
I have the below method and I want to call it and return the array data in another method but that does not work. but the self in the other method returns no data?
- (NSMutableArray *)glo
{
NSMutableArray *globalarray = [[NSMutableArray array]init];
for (int x = 0; x < 10; x++) {
[globalarray addObject: [NSNumber numberWithInt: arc4random()%200]];
return globalarray ;
}
}
-(IBAction)clicked_insertsort:(id)sender{
[self glo];
}
Upvotes: 0
Views: 92
Reputation: 24041
I really try to replace some part in your code to something like this:
- (NSMutableArray *)glo
{
NSMutableArray *globalarray = [[NSMutableArray array] init];
for (int x = 0; x < 10; x++) {
[globalarray addObject:[NSNumber numberWithInt: arc4random()%200]];
}
return globalarray; // pull out from the loop
}
and this:
-(IBAction)clicked_insertsort:(id)sender{
NSMutableArray *array = [self glo]; // take care of the return value
NSLog(@"array : %@", array)
}
UPDATE:
if you want a global variable in you class you should define the following:
@interface YourClass : NSObject {
NSMutableArray *globalarray;
}
// ...
@end
and the methods will be the following (no return value needed, because the variable is available from the whole class now)
- (void)glo {
if (!globalarray) {
globalarray = [NSMutableArray array];
for (int x = 0; x < 10; x++) {
[globalarray addObject:[NSNumber numberWithInt: arc4random()%200]];
}
}
}
Upvotes: 2