I have a method which has gotten a little long & I want to place it in its own file. It’s not useful outside the program I’m working on, I really just want to remove it so that my code is more readable.
The method is below,
- (void)randomiseAudioIndicesBeforeInitialPlay
{
int numberOfStems = 20;
index = malloc(numberOfStems*sizeof(int));
for (int i = 0; i < numberOfStems; i++)
{
index[i] = i;
}
for (int i = (numberOfStems - 1); i > 0; i--)
{
int randomIndex = arc4random() % i;
int tmp = index[i];
index[i] = index[randomIndex];
index[randomIndex] = tmp;
}
}
I tried making a subclass as per this previous question
//RandomiseStems.h
#import <Foundation/Foundation.h>
@interface RandomiseStems : UIViewController {
int *index;
}
@property(nonatomic, readwrite) int *index;
- (void)randomiseAudioIndicesBeforeInitialPlay;
@end
//RandomiseStems.m
#import "RandomiseStems.h"
@implementation RandomiseStems
@synthesize index;
- (void)randomiseAudioIndicesBeforeInitialPlay
{
NSLog(@"randomise called");
int numberOfStems = 20;
//int* index = malloc(numberOfStems*sizeof(int));
index = malloc(numberOfStems*sizeof(int));
for (int i = 0; i < numberOfStems; i++)
{
index[i] = i;
}
for (int i = (numberOfStems - 1); i > 0; i--)
{
int randomIndex = arc4random() % i;
int tmp = index[i];
index[i] = index[randomIndex];
index[randomIndex] = tmp;
//free index
}
}
@end
I then import the .h into my viewController.h file & my .m file into my viewController.m file. It’s builds ok but when I try to call randomiseAudioIndicesBeforeInitalPlay it throws an exception (i used
[self randomiseAudioIndicesBeforeInitalPlay];)
Is this a valid way to do this? if so any ideas on how it might be fixed? thanks in advance 🙂
If you just want to move a method, or a few, a Category is the way to go, that is what they are designed for. What you can’t do is create any new ivars.